|
1 | 1 | import BigNumber from "bignumber.js" |
2 | 2 |
|
| 3 | +import { ROUNDING_MAP } from "./rounding" |
| 4 | + |
3 | 5 | const DEFAULT_PRECISION = 2 |
4 | 6 | const DEFAULT_DELIMITER = "," |
5 | 7 | const DEFAULT_SEPARATOR = "\xA0" |
| 8 | +const DEFAULT_ROUNDING = "ROUND_DOWN" |
| 9 | + |
| 10 | +export const Number = ({ |
| 11 | + value, |
| 12 | + enforcePrecision = true, |
| 13 | + precision = DEFAULT_PRECISION, |
| 14 | + roundingMode = DEFAULT_ROUNDING, |
| 15 | + delimiter = DEFAULT_DELIMITER, |
| 16 | + separator = DEFAULT_SEPARATOR, |
| 17 | +}) => { |
| 18 | + const bnRounding = |
| 19 | + ROUNDING_MAP[roundingMode] ?? ROUNDING_MAP[DEFAULT_ROUNDING] |
6 | 20 |
|
7 | | -export const Number = ({ value, enforcePrecision = true, ...options }) => { |
8 | | - const instance = new BigNumber(value) |
9 | | - const format = { groupSize: 3 } |
| 21 | + const instance = new BigNumber(value).decimalPlaces( |
| 22 | + precision, |
| 23 | + bnRounding, |
| 24 | + ) |
10 | 25 |
|
11 | | - const precision = options.precision == null ? DEFAULT_PRECISION : options.precision |
12 | | - format.decimalSeparator = options.delimiter == null ? DEFAULT_DELIMITER : options.delimiter |
13 | | - format.groupSeparator = options.separator == null ? DEFAULT_SEPARATOR : options.separator |
| 26 | + const format = { |
| 27 | + groupSize: 3, |
| 28 | + decimalSeparator: delimiter, |
| 29 | + groupSeparator: separator, |
| 30 | + } |
14 | 31 |
|
15 | 32 | const string = instance.toFormat(precision, undefined, format) |
16 | 33 |
|
17 | 34 | return enforcePrecision |
18 | 35 | ? string |
19 | | - : string.replace(new RegExp(`(\\${DEFAULT_DELIMITER}\\d+)0+`), "$1") |
| 36 | + : string.replace(new RegExp(`(\\${delimiter}\\d+)0+`), "$1") |
20 | 37 | } |
0 commit comments