@0xtorch/big-decimal
Version:
An arbitrary precision Decimal type for TypeScript that extends BigInt.
28 lines (25 loc) • 988 B
text/typescript
import type { BigDecimal } from './type'
export const toStringBigDecimal = ({ value, decimals }: BigDecimal): string => {
if (value === 0n) {
return '0'
}
const isNegative = value < 0
const prefix = isNegative ? '-' : ''
const absValue = isNegative ? -value : value
const valueText = absValue.toString()
const valueLength = valueText.length
const decimalLength = decimals
if (valueLength <= decimalLength) {
const text = `0.${valueText.padStart(decimalLength, '0')}`
const formattedText = text.replace(/0+$/, '')
return `${prefix}${formattedText}`
}
const intText = valueText.slice(0, valueLength - decimalLength)
const decimalText = valueText.slice(valueLength - decimalLength)
// decimal 末尾の 0 は削除 (正規表現で良い感じに)
const formattedDecimalText = decimalText.replace(/0+$/, '')
if (formattedDecimalText.length === 0) {
return `${prefix}${intText}`
}
return `${prefix}${intText}.${formattedDecimalText}`
}