我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
parseFloat(“1.555”).toFixed(2);//返回1.55而不是1.56。
1.55是绝对正确的结果,因为在计算机中不存在1.555的精确表示。如果读数为1.555,则四舍五入至最接近的值=1.55499999999999994(64位浮点)。将这个数字四舍五入到Fixed(2)得到1.55。
如果输入为1.55499999999999,则此处提供的所有其他功能都会给出故障结果。
解决方案:在扫描前加上数字“5”,将数字舍入(更准确地说,从0开始舍入)。仅当数字真的是浮点(有小数点)时才执行此操作。
parseFloat("1.555"+"5").toFixed(2); // Returns 1.56
其他回答
这项看似简单的任务面临的最大挑战是,我们希望它能够产生心理预期的结果,即使输入包含最小的舍入误差(更不用说计算中会出现的误差)。如果我们知道实际结果正好是1.005,那么我们预计舍入到两位数会得到1.01,即使1.005是一个带有大量舍入误差的大型计算的结果。
当处理floor()而不是round()时,问题变得更加明显。例如,当删除33.3点后面的最后两位数字后的所有内容时,我们肯定不会期望得到33.29,但这就是结果:
console.log(数学楼层(33.3*100)/100)
在简单的情况下,解决方案是对字符串而不是浮点数执行计算,从而完全避免舍入错误。然而,这个选项在第一次非平凡的数学运算(包括大多数除法运算)时失败,而且速度很慢。
当对浮点数进行操作时,解决方案是引入一个参数,该参数指定我们愿意偏离实际计算结果的量,以便输出心理预期的结果。
var round=函数(num,数字=2,compensateErrors=2){如果(num<0){return this.round(-num,数字,compensateErrors);}const pow=数学.pow(10,数字);return(数学舍入(num*pow*(1+compensateErrors*Number.EPSILON))/pow);}/*---测试---*/console.log(“本线程中提到的边缘案例:”)var值=[0.015,1.005,5.555,156893.145,362.42499999999995,1.275,1.277499,1.2345678e+2,2.175,5.015,58.9*0.15];值。对于每个((n)=>{console.log(n+“->”+圆(n));console.log(-n+“->”+圆形(-n));});console.log(“\n对于太大以至于无法在计算精度范围内执行舍入的数字,只有基于字符串的计算才有帮助。”)console.log(“标准:”+圆形(1e+19));console.log(“补偿=1:”+圆(1e+19,2,1));console.log(“有效无补偿:”+round(1e+19,2,0.4));
注意:Internet Explorer不知道Number.EPSILON。如果您仍然需要支持它,那么您可以使用垫片,或者自己定义特定浏览器系列的常量。
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46
对这个答案稍作修改,似乎效果不错。
作用
function roundToStep(value, stepParam) {
var step = stepParam || 1.0;
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
用法
roundToStep(2.55) = 3
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
这是astorije的答案的修改版本,更好地支持负值舍入。
// https://stackoverflow.com/a/21323513/384884
// Modified answer from astorije
function round(value, precision) {
// Ensure precision exists
if (typeof precision === "undefined" || +precision === 0) {
// Just do a regular Math.round
return Math.round(value);
}
// Convert the value and precision variables both to numbers
value = +value;
precision = +precision;
// Ensure the value is a number and that precision is usable
if (isNaN(value) || !(typeof precision === "number" && precision % 1 === 0)) {
// Return NaN
return NaN;
}
// Get the sign of value
var signValue = Math.sign(value);
// Get the absolute value of value
value = Math.abs(value);
// Shift
value = value.toString().split("e");
value = Math.round(+(value[0] + "e" + (value[1] ? (+value[1] + precision) : precision)));
// Shift back
value = value.toString().split("e");
value = +(value[0] + "e" + (value[1] ? (+value[1] - precision) : -precision));
// Apply the sign
value = value * signValue;
// Return rounded value
return value;
}
我回顾了这篇文章的每一个答案。以下是我对此事的看法:
常量nbRounds=7;常量舍入=(x,n=2)=>{常量精度=数学.pw(10,n)return数学舍入((x+Number.EPSILON)*precision)/精度;}设i=0;而(nbRounds>i++){console.log(“round(1.00083899,”,i,“)>”,round(1.00 08389,i))console.log(“圆形(1.83999305,”,i,“)>”,圆形(1.83999305,i))}