我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
简单的通用舍入函数如下:
步骤如下:
使用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
其他回答
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46
我正在构建一个简单的tipCalculator,这里有很多答案似乎使问题过于复杂。所以我发现总结这个问题是真正回答这个问题的最佳方式。
如果要创建舍入的十进制数,首先调用Fixed(要保留的小数位数),然后将其包装在number()中。
最终结果是:
let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip) // 57.29 instead of 57.288
将类型保留为整数,以便以后进行排序或其他算术运算:
Math.round(1.7777777 * 100)/100
1.78
// Round up!
Math.ceil(1.7777777 * 100)/100
1.78
// Round down!
Math.floor(1.7777777 * 100)/100
1.77
或转换为字符串:
(1.7777777).toFixed(2)
"1.77"
这对正数、负数和大数都适用:
function Round(value) {
const neat = +(Math.abs(value).toPrecision(15));
const rounded = Math.round(neat * 100) / 100;
return rounded * Math.sign(value);
}
//0.244 -> 0.24
//0.245 -> 0.25
//0.246 -> 0.25
//-0.244 -> -0.24
//-0.245 -> -0.25
//-0.246 -> -0.25
当我想一直舍入到某个小数点时,这对我来说非常有效。这里的关键是,我们将始终使用Math.ceil函数进行舍入。
如果需要,可以有条件地选择天花板或地板。
/***在大量数据时可能失去精度*@param编号*@return数字*/var roundUpToNearestHundredth=函数(数字){//确保我们使用高精度数字number=数量(number);//保存原始数字,这样当我们提取第一百位小数时,就不会进行位切换或丢失精度var numberSave=数字(Number.toFixed(0));//删除数字顶部的“整数”值number=number-number保存;//获取小数点后一百位数量*=100;//终止小数。因此,15000001将等于151等。number=数学ceil(数字);//把小数放回正确的位置数量/=100;//将“整数”加回到数字上return number+numberSave;};console.log(roundUpToNearestHundredth(6132423.1200000000001))