Converting Floating Point Numbers To Integers, Rounding To 2 Decimals In Javascript
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 ->
Solution 1:
One way to do this is to use the toFixed
method off a Number combined with parseFloat
.
Eg,
varnumber = 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,
varnumber = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2)) * 100;
console.log(truncated);
Post a Comment for "Converting Floating Point Numbers To Integers, Rounding To 2 Decimals In Javascript"