[英]javascript - convert number to a float with precision of 2
I am using Javascript and need to convert a number like 0.009 into a number 0.90.我正在使用 Javascript 并且需要将像 0.009 这样的数字转换为数字 0.90。
I am trying to do the below, but it only returns 0.9: parseFloat((testValue * 100).toFixed(2))
我正在尝试执行以下操作,但它只返回 0.9:
parseFloat((testValue * 100).toFixed(2))
For numbers like 0.0055, it is giving me 0.55, but for 0.009/0.008/0.007 etc, it is giving me 0.9/0.8/0.7 or in other words number with a precision of 1 after decimal.对于像 0.0055 这样的数字,它给了我 0.55,但对于 0.009/0.008/0.007 等,它给了我 0.9/0.8/0.7 或者换句话说,小数点后精度为 1 的数字。
How can I make it return 2 precision after decimal point?如何让它在小数点后返回 2 精度? For eg, I want the code to return 0.90 for 0.009, 0.80 for 0.008 and so on..
例如,我希望代码为 0.009 返回 0.90,为 0.008 返回 0.80,依此类推。
Any help would be greatly appreciated.任何帮助将不胜感激。
Just call toFixed(2)
, without calling parseFloat()
.只需调用
toFixed(2)
,而不调用parseFloat()
。 parseFloat()
is converting the formatted number back into a floating point number, and they don't have different precisions. parseFloat()
将格式化的数字转换回浮点数,它们没有不同的精度。
let num =.009; console.log((num * 100).toFixed(2)); console.log(parseFloat((num * 100).toFixed(2)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.