我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
这里有一个简单的方法:
Math.round(value * 100) / 100
不过,您可能需要继续创建一个单独的函数来为您执行此操作:
function roundToTwo(value) {
return(Math.round(value * 100) / 100);
}
然后,只需传入值。
通过添加第二个参数,可以将其增强为任意小数位数。
function myRound(value, places) {
var multiplier = Math.pow(10, places);
return (Math.round(value * multiplier) / multiplier);
}
其他回答
如果值是文本类型:
parseFloat("123.456").toFixed(2);
如果值是数字:
var numb = 123.23454;
numb = numb.toFixed(2);
有一个缺点,像1.5这样的值将给出“1.50”作为输出。@minitech建议的修复方法:
var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.
Math.round似乎是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:
Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!
toFixed()在某些情况下也不会正确舍入(在Chrome v.55.0.2883.87中测试)!
示例:
parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.
1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.
我想,这是因为1.555实际上就像是幕后的浮球1.55499994。
解决方案1是使用具有所需舍入算法的脚本,例如:
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
它也在Plunker。
注意:这并不是每个人都能通用的解决方案。有几种不同的舍入算法。您的实现可能不同,这取决于您的需求。请参见舍入。
解决方案2是避免前端计算,并从后端服务器提取舍入值。
另一种可能的解决方案,也不是防弹的。
Math.round((num + Number.EPSILON) * 100) / 100
在某些情况下,当您舍入像1.3549999999999998这样的数字时,它将返回错误的结果。它应该是1.35,但结果是1.36。
在这里,我使用了三元运算符来检查数字是否具有小数。如果没有,我只需返回数字。
否则,我使用Intl.NumberFormat构造函数获取所需的值。
Intl.NumberFormat是ECMAScript国际化API规范(ECMA402)的一部分。它有很好的浏览器支持,甚至包括IE11,并且在Node.js中完全支持。
const numberFormatter=新Intl.NumberFormat('en-US'{minimumFractionDigits:2,最大分数位数:2,});函数getRoundedNumber(number){return number.toString().indexOf(“.”)==-1?number:numberFormatter.format(数字);}console.log(getRoundedNumber(10));console.log(getRoundedNumber(1.7777777));console.log(getRoundedNumber(9.1));console.log(getRoundedNumber(2.345));console.log(getRoundedNumber(2.2095));console.log(getRoundedNumber(2.995));
问题是四舍五入到两位小数。
让我们不要把这个复杂化,修改原型链等。
以下是单线解决方案
让round2dec=num=>数学舍入(num*100)/100;控制台日志(round2dec(1.77));控制台日志(round2dec(1.774));控制台日志(round2dec(1.777));console.log(round2dec(10));
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
请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。
var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));