我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我正在构建一个简单的tipCalculator,这里有很多答案似乎使问题过于复杂。所以我发现总结这个问题是真正回答这个问题的最佳方式。
如果要创建舍入的十进制数,首先调用Fixed(要保留的小数位数),然后将其包装在number()中。
最终结果是:
let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip) // 57.29 instead of 57.288
其他回答
MarkG的答案是正确的。这里是任何小数位数的通用扩展。
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
用法:
var n = 1.7777;
n.round(2); // 1.78
单元测试:
it.only('should round floats to 2 places', function() {
var cases = [
{ n: 10, e: 10, p:2 },
{ n: 1.7777, e: 1.78, p:2 },
{ n: 1.005, e: 1.01, p:2 },
{ n: 1.005, e: 1, p:0 },
{ n: 1.77777, e: 1.8, p:1 }
]
cases.forEach(function(testCase) {
var r = testCase.n.round(testCase.p);
assert.equal(r, testCase.e, 'didn\'t get right number');
});
})
简单的通用舍入函数如下:
步骤如下:
使用Math.pow(10,位)将数字乘以(10乘以小数位数的幂)。使用Math.Round将结果舍入为整数。将结果除以(10乘以小数位数的幂)Math.pow(10,位)。
例子:
数字为:1.2375四舍五入至小数点后三位
1.2375 * (10^3) ==> 1.2375 * 1000 = 1237.5舍入为整数==>1238将1238除以(10^3)==>1238/1000=1.238
(注:10^3表示数学功率(10,3))。
函数编号RoundDecimal(v,n){return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(1,n)}//-------测试--------console.log(numberRoundDecimal(-0.0246411603862896567,3))//-0.025console.log(numberRoundDecimal(0.9993360575508052,3))//0.999console.log(numberRoundDecimal(1.0020739645577939,3))//1.002console.log(numberRoundDecimal(0.975,0))//1console.log(numberRoundDecimal(0.975,1))//1console.log(numberRoundDecimal(0.975,2))//0.98console.log(numberRoundDecimal(1.005,2))//1.01
具有可读选项的函数更直观:
function round_number(options) {
const places = 10**options.decimal_places;
const res = Math.round(options.number * places)/places;
return(res)
}
用法:
round_number({
number : 0.5555555555555556,
decimal_places : 3
})
0.556
这个函数对我有用。你只需输入数字和你想要舍入的位置,它就可以轻松地完成所需的操作。
round(source, n) {
let places = Math.pow(10, n);
return Math.round(source * places) / places;
}
有一种解决方案适用于所有数字。试试看。表达式如下所示。
Math.round((num + 0.00001) * 100) / 100.
Try Below Ex:
Math.round((1.005 + 0.00001) * 100) / 100
Math.round((1.0049 + 0.00001) * 100) / 100
我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。
这是计算过程中出现的问题的屏幕截图,
.
转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。