简体   繁体   English

将浮点数转换为整数,并在JavaScript中舍入为2个小数

[英]Converting floating point numbers to integers, rounding to 2 decimals in JavaScript

What's the best way to perform the following conversions in JavaScript? 在JavaScript中执行以下转换的最佳方法是什么? I have currencies stored as floats that I want rounded and converted to integers. 我将货币存储为浮点数,希望将其四舍五入并转换为整数。

1501.0099999999999909 -> 150101 1501.0099999999999909 > 150101

12.00000000000001 -> 1200 12.00000000000001 > 1200

One way to do this is to use the toFixed method off a Number combined with parseFloat . 一种方法是将Number与parseFloat结合使用toFixed方法。

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. toFixed接受应截断的小数点位数。

To get the output you need, you would only need `toFixed(2)' and multiple the result by 100. 要获得所需的输出,您只需要`toFixed(2)'并将结果乘以100。

Eg, 例如,

var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2)) * 100;
console.log(truncated);

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

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