[英]Javascript - toFixed() 0.5 issue
I have a case where I want to round decimal number by 2 decimal places. 我有一种情况,我想将小数点后两位小数舍入。 For now .toFixed(2) is working fine, however for 0.455 I want to get 0.45 and not 0.46
目前.toFixed(2)可以正常工作,但是对于0.455,我想得到0.45,而不是0.46
Is there any quick solution for this? 有什么快速解决方案吗? I can use Lodash if it can solve this.
如果可以解决此问题,我可以使用Lodash。
For example I want the followings. 例如,我想要以下内容。
0.455 > 0.45 0.455> 0.45
0.456 > 0.46 0.456> 0.46
0.4549 > 0.45 0.4549> 0.45
Multiply by 100, round down with floor, divide with 100, format with toFixed. 乘以100,向下取整,向下取100,除以toFixed。
function roundDownToFixed2(v) {
return (Math.floor(v * 100) / 100).toFixed(2);
}
> roundDownToFixed2(0.455)
'0.45'
A more generic version would be 一个更通用的版本是
function roundDownToFixed(v, d=2) {
const mul = Math.pow(10, d);
return (Math.floor(v * mul) / mul).toFixed(d);
}
> roundDownToFixed(0.455, 2)
'0.45'
> roundDownToFixed(0.4555, 3)
'0.455'
this should help: 这应该有助于:
function roundDecimal(a, k) {
let K = Math.pow(10, k);
return Math.round(a * K) / K;
}
so roundDecimal(0.455, 2)
would be 0.46
所以
roundDecimal(0.455, 2)
将是0.46
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.