将浮点数转换为整数,在JavaScript中舍入到2位小数 [英] Converting floating point numbers to integers, rounding to 2 decimals in JavaScript
问题描述
在JavaScript中执行以下转换的最佳方法是什么?
1501.0099999999999909
- > 150101
12.00000000000001
- > 1200
执行此操作的一种方法是使用 toFixed
方法关闭一个数字加上 parseFloat
。
例如,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(5));
console.log(截断);
toFixed
取小数点它应该被截断。
为了得到你需要的输出,你只需要`toFixed(2)'和多个结果乘以100。例如,b
$ b
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2))* 100;
console.log(截断);
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
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);
这篇关于将浮点数转换为整数,在JavaScript中舍入到2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!