decimal-fns
Useful functions to make working with Decimal.js more enjoyable.
Installation
npm i decimal-fns decimal.js
NOTE: This package relies on Decimal.js as a Peer Dependency and does not bundle it as part of this repository.
Usage
import { asDecimal, formatNumber, humanNumber, isDecimal} from 'decimal-fns'
const number = 5
const decimal = asDecimal(5)
const biggerDecimal = decimal.plus("2000")
isDecimal(biggerDecimal)
formatNumber(biggerDecimal)
humanNumber(biggerDecimal.times(100))
Exported Methods
asDecimal(value, [fallback])
Converts a Decimal-Like param (string, number, Decimal) and attempts to convert it to the Decimal type. If the conversion fails (e.g. NaN is provided), it will attempt to return the fallback parameter as a Decimal. If no fallback is provided, or if the fallback can not be converted to a Decimal (e.g. NaN is provided), then the method will throw.
import { asDecimal } from 'decimal-fns'
const value = "5"
const decimal = asDecimal(value, 0)
const fallback = asDecimal(undefined, 0)
isDecimal(value)
Determines if a parameter is a Decimal type, while also indicating to the Typescript parser to treat the item as a Decimal going forward.
import { isDecimal } from 'decimal-fns'
isDecimal(5)
isDecimal(new Decimal(5))
formatNumber(value, { numDecimals })
Format a number with thousands separators and a fixed number of decimal places.
import { formatNumber } from 'decimal-fns'
formatNumber(5)
formatNumber(5000.555555, { numDecimals: 1 })
formatNumber(1234567890)
humanNumber(value, { useWords })
Convert a Decimal-Like param (string, number, Decimal) to a human-readable number in a string.
import { humanNumber } from 'decimal-fns'
humanNumber(5)
humanNumber(new Decimal(5000))
humanNumber(1234, { useWords: true })
humanNumber("1234560")
humanNumber(1234567890)
humanNumber(1_234_560_000_000)
Brought to you by M2 Labs
This project is maintained and funded by M2 Labs, a Web3 product development studio.