问题
What's the best way to perform the following conversions in JavaScript? I have currencies stored as floats that I want rounded and converted to integers.
1501.0099999999999909
-> 150101
12.00000000000001
-> 1200
回答1:
One way to do this is to use the toFixed
method off a Number combined with parseFloat
.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(5));
console.log(truncated);
toFixed
takes in the number of decimal points it should be truncated to.
To get the output you need, you would only need `toFixed(2)' and multiple the result by 100.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2)) * 100;
console.log(truncated);
来源:https://stackoverflow.com/questions/30249706/converting-floating-point-numbers-to-integers-rounding-to-2-decimals-in-javascr