不要去除 JavaScript 十进制构造函数中的尾随零
Do not strip trailing zeros in JavaScript Decimal constructor
我有代表金钱的字符串。例如 29.00 或 29.10 或 29.13,但货币可以更改并且不一定导致默认情况下具有两位小数的值(例如日元根本没有小数位)
现在,我使用 Decimal.js 对这些值执行计算
例如我乘以一个百分比
let d = new decimal("29.00")
let e = d.mul(0.133333333333).toDP(d.decimalPlaces())
然而,由于构造函数去除尾随零并将 decimalPlaces 设置为 0,因此结果四舍五入到小数点后 0 位。
我怎样才能得到一个十进制值,它总是有输入字符串提供的小数位数?在这个例子中 d.decimalPlaces 应该 return 2(因为 29.00 必须有小数位)。
替代解决方案:如何从字符串中提取小数位数?
你是这个意思?
const keepDecimal = (str,mul) => {
const dec = str.split(".");
const numDec = dec.length===2?dec[1].length:0;
return (str*mul).toFixed(numDec);
}
console.log(keepDecimal("29.13",0.133333333333))
console.log(keepDecimal("29",0.133333333333))
我有代表金钱的字符串。例如 29.00 或 29.10 或 29.13,但货币可以更改并且不一定导致默认情况下具有两位小数的值(例如日元根本没有小数位)
现在,我使用 Decimal.js 对这些值执行计算
例如我乘以一个百分比
let d = new decimal("29.00")
let e = d.mul(0.133333333333).toDP(d.decimalPlaces())
然而,由于构造函数去除尾随零并将 decimalPlaces 设置为 0,因此结果四舍五入到小数点后 0 位。
我怎样才能得到一个十进制值,它总是有输入字符串提供的小数位数?在这个例子中 d.decimalPlaces 应该 return 2(因为 29.00 必须有小数位)。
替代解决方案:如何从字符串中提取小数位数?
你是这个意思?
const keepDecimal = (str,mul) => {
const dec = str.split(".");
const numDec = dec.length===2?dec[1].length:0;
return (str*mul).toFixed(numDec);
}
console.log(keepDecimal("29.13",0.133333333333))
console.log(keepDecimal("29",0.133333333333))