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

梦想与她 提交于 2020-01-05 11:30:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!