A Millwork codec factory for exact decimals with decimal.js, big.js or bignumber.js.
Install one of the three libraries.
pnpm add @millwork-ts/decimal @millwork-ts/core decimal.js
This package has one factory, decimalCodec(lib). Give it the Decimal, Big or BigNumber
constructor. It gives a codec with the name big-decimal. Give a second argument to use another name. The default name does not clash with the decimal codec of @millwork-ts/core.
import Decimal from 'decimal.js'
import { decimalCodec } from '@millwork-ts/decimal'
export const decimal = decimalCodec(Decimal)
| Codec | Value | Raw |
|---|---|---|
decimal |
an instance of the library that you give it | "123.45"; a number on read only |
"1e21", is accepted.19.99. It never writes a number."1000000000000000000000".NaN and Infinity are bad input."123.4500" writes back as "123.45". Use the
scale option to keep a fixed number of digits.The package has no ready codec, because the three libraries are optional peers. A ready codec would import a library that you possibly do not have.
| Option | Type | Use |
|---|---|---|
scale |
number |
The number of digits after the point on serialize. It never rounds: it throws a RangeError if digits are lost. |
equals uses the eq method of the library. 1.50 equals 1.5.
Register the codecs before the store calls transformations(), because transformations()
reads the registry when it runs. See the
@millwork-ts/warp-drive README.
import Decimal from 'decimal.js'
import { decimalCodec } from '@millwork-ts/decimal'
import { registerCodecs, valueField } from '@millwork-ts/warp-drive'
import { withDefaults } from '@warp-drive/core/reactive'
registerCodecs({ 'big-decimal': decimalCodec(Decimal) })
export const InvoiceSchema = withDefaults({
type: 'invoice',
fields: [valueField('taxRate', 'big-decimal', { scale: 4 })],
})