Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何更改JavaScript中的数字舍入规则?_Javascript_Math_Tofixed - Fatal编程技术网

如何更改JavaScript中的数字舍入规则?

如何更改JavaScript中的数字舍入规则?,javascript,math,tofixed,Javascript,Math,Tofixed,在JavaScript中使用toFixed(2)方法的结果如下: 3,123 = 3,12 3,124 = 3,12 3,125 = 3,13 3,126 = 3,13 这当然是正确的,但我想改变当逗号后出现5个数字时,四舍五入(增加)数字的规则。因此,我希望得到以下结果: 3,123 = 3,12 3,124 = 3,12 **3,125 = 3,12** (don't increase the number) 3,126 = 3,13 如何在JavaScript中实现这一点?您只需使用

在JavaScript中使用toFixed(2)方法的结果如下:

3,123 = 3,12
3,124 = 3,12
3,125 = 3,13
3,126 = 3,13 
这当然是正确的,但我想改变当逗号后出现5个数字时,四舍五入(增加)数字的规则。因此,我希望得到以下结果:

3,123 = 3,12
3,124 = 3,12
**3,125 = 3,12** (don't increase the number)
3,126 = 3,13

如何在JavaScript中实现这一点?

您只需使用基本数学和解析即可:

parseInt(number * 100, 10) / 100; //10 param is optional
对于每个精度,添加一个小数步。

功能自定义汇总(数字){
//把数字串起来,这样我们就可以处理字符串了
const stringified=numbers.map(x=>x.toString());
返回stringified.map((x)=>{
//看看我们是否符合你的5号特例
//如果没有,请使用常规的toFixed()
如果(x[x.length-1]!='5'){
返回parseFloat(x).toFixed(2);
}
//如果我们这样做了,从等式中去掉5,并将其四舍五入
//因此,它将把它从高到低
返回parseFloat(x.substring(0,x.length-1)).toFixed(2);
});
}
常数数=[
3.123,
3.124,
3.125,
3.126,
];

console.log(customRoundUp(数字))对于那些不喜欢parseInt的人:

function customRound(number, numDecimal)
{
    var x = number - 1/Math.pow(10, numDecimal + 1);
    return x.toFixed(numDecimal);
}
想法是,将要舍入的数字减少0.001(在toFixed(2)的情况下)

但是我写这个函数是为了更一般的用途,所以看起来很复杂。 如果您只想使用.toFixed(2),那么customRound可以编写为:

function customRound(number)
{
    var x = number - 0.001;
    return x.toFixed(2);
}

问题不清楚。注意:数字的四舍五入几乎应该始终被视为一个演示问题,即当将计算的最终结果转换为字符串以供显示时。中间计算不应四舍五入。