@0xtorch/big-decimal
Version:
An arbitrary precision Decimal type for TypeScript that extends BigInt.
41 lines (36 loc) • 953 B
text/typescript
import { removeTrailingZeros } from './removeTrailingZeros'
import type { BigDecimal } from './type'
export const fix = (
{ value, decimals }: BigDecimal,
fixDecimals: number,
rounding: 'round' | 'floor' | 'ceil',
): BigDecimal => {
if (decimals <= fixDecimals) {
return removeTrailingZeros({ value, decimals })
}
const fixPlusOneValue = value / 10n ** BigInt(decimals - fixDecimals - 1)
const fixValue = round(fixPlusOneValue, rounding)
return removeTrailingZeros({
value: fixValue,
decimals: fixDecimals,
})
}
const round = (value: bigint, rounding: 'round' | 'floor' | 'ceil'): bigint => {
switch (rounding) {
case 'ceil': {
if (value < 0n) {
return (value - 9n) / 10n
}
return (value + 9n) / 10n
}
case 'floor': {
return value / 10n
}
case 'round': {
if (value < 0n) {
return (value - 5n) / 10n
}
return (value + 5n) / 10n
}
}
}