简体   繁体   English

不要去除 JavaScript 十进制构造函数中的尾随零

[英]Do not strip trailing zeros in JavaScript Decimal constructor

i have strings that represents money.我有代表钱的字符串。 Eg 29.00 or 29.10 or 29.13 the currency however can change and does not necessarily lead to a value that has two decimal places by default (Yen for example does not have decimal places at all)例如 29.00 或 29.10 或 29.13 货币但是可以改变并且不一定导致默认情况下具有两位小数的值(例如日元根本没有小数位)

Now, i use Decimal.js to execute calculations with these values现在,我使用 Decimal.js 使用这些值执行计算

For example i am multiplying with a percentage例如,我乘以百分比

let d = new decimal("29.00")
let e = d.mul(0.133333333333).toDP(d.decimalPlaces())

The result of this however is rounded to 0 decimal places as the constructer strips away the trailing zeros and sets decimalPlaces to 0.然而,这个结果被舍入到小数点后 0 位,因为构造函数去掉了尾随的零并将 decimalPlaces 设置为 0。

How can i get a decimal value that always has to amount of decimal places provided by the input string?我怎样才能得到一个总是必须输入字符串提供的小数位数的十进制值? In this example d.decimalPlaces should return 2 (because 29.00 has to decimal places).在此示例中,d.decimalPlaces 应返回 2(因为 29.00 必须保留小数位)。

Alternative solution: How do i extract the number of decimal places out of the string?替代解决方案:如何从字符串中提取小数位数?

You mean this?你是这个意思?

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM