我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我只是想根据前面提到的答案分享我的方法:
让我们创建一个函数,将任何给定的数值舍入到给定的小数位数:
function roundWDecimals(n, decimals) {
if (!isNaN(parseFloat(n)) && isFinite(n)) {
if (typeof(decimals) == typeof(undefined)) {
decimals = 0;
}
var decimalPower = Math.pow(10, decimals);
return Math.round(parseFloat(n) * decimalPower) / decimalPower;
}
return NaN;
}
并为数字原型引入一种新的“舍入”方法:
Object.defineProperty(Number.prototype, 'round', {
enumerable: false,
value: function(decimals) {
return roundWDecimals(this, decimals);
}
});
您可以测试它:
函数舍入WDecimals(n,小数){if(!isNaN(parseFloat(n))&&isFinite(n){if(typeof(小数)==typeof(未定义)){小数=0;}var decimalPower=数学.pow(10,小数);return Math.round(parseFloat(n)*decimalPower)/decimalPower;}返回NaN;}Object.defineProperty(Number.prototype,'round'{可枚举:false,值:函数(小数){返回舍入WDecimals(this,小数);}});var舍入=[{num:10,小数:2},{num:1.7777777,小数:2},{num:9.1,小数:2},{num:55.55,小数:1},{num:55.549,小数:1},{num:55,小数:0},{num:54.9,小数:0},{num:-55.55,小数:1},{num:-55.551,小数:1},{num:-55,小数:0},{num:1.005,小数:2},{num:1.005,小数:2},{num:198000000007,小数:2},],table='<table border=“1”><tr><th>Num</th><th>小数</th><th>结果</th></tr>';$.each(roundables,function(){表+='<tr>'+“<td>”+此.num+“</td>”+“<td>”+此小数+“</td>”+'<td>'+this.num.round(this.decimals)+'</td>'+'</tr>';});table+=“</table>”;$('.results').append(表);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><div class=“results”></div>
其他回答
要在小数位置pos(不包括小数)舍入,请执行Math.rround(num*Math.pow(10,pos))/Math.pow(1,pos
var控制台={日志:函数{document.getElementById(“控制台”).innerHTML+=s+“<br/>”}}var roundDecimals=函数(num,pos){return(Math.round(num*Math.pow(10,pos))/Math.pop(10,pos));}//https://en.wikipedia.org/wiki/Pivar pi=3.14159265358979323846264338327950288419716939937510;对于(var i=2;i<15;i++)console.log(“pi=”+roundDecimals(pi,i));对于(var i=15;i>=0;--i)console.log(“pi=”+roundDecimals(pi,i));<div id=“console”/>
只有在必要时才能实现这种舍入的一种方法是使用Number.protype.toLocaleString():
myNumber.toLocaleString('en', {maximumFractionDigits:2, useGrouping:false})
这将提供您期望的输出,但是是字符串。如果不是您期望的数据类型,您仍然可以将它们转换回数字。
它可能对你有用,
Math.round(num * 100)/100;
了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46
当我想一直舍入到某个小数点时,这对我来说非常有效。这里的关键是,我们将始终使用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))