我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
要不处理许多0,请使用以下变体:
Math.round(num * 1e2) / 1e2
其他回答
我知道有很多答案,但大多数答案在某些特定情况下都有副作用。
没有任何副作用的最简单和最短的解决方案如下:
Number((2.3456789).toFixed(2)) // 2.35
它正确舍入并返回数字而不是字符串
console.log(Number((2.345).toFixed(2))) // 2.35
console.log(Number((2.344).toFixed(2))) // 2.34
console.log(Number((2).toFixed(2))) // 2
console.log(Number((-2).toFixed(2))) // -2
console.log(Number((-2.345).toFixed(2))) // -2.35
console.log(Number((2.345678).toFixed(3))) // 2.346
要在小数位置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”/>
我创建了这个函数,用于舍入数字。该值可以是字符串(例如“1.005”)或数字1.005,默认值为1,如果指定小数为2,则结果为1.01
round(value: string | number, decimals: number | string = "0"): number | null {
return +( Math.round(Number(value + "e+"+decimals)) + "e-" + decimals);
}
用法:round(1.005,2)//1.01或用法:round('1.005',2)//1.01
当我想一直舍入到某个小数点时,这对我来说非常有效。这里的关键是,我们将始终使用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))
我尝试了自己的代码。试试看:
function AmountDispalyFormat(value) {
value = value.toFixed(3);
var amount = value.toString().split('.');
var result = 0;
if (amount.length > 1) {
var secondValue = parseInt(amount[1].toString().slice(0, 2));
if (amount[1].toString().length > 2) {
if (parseInt(amount[1].toString().slice(2, 3)) > 4) {
secondValue++;
if (secondValue == 100) {
amount[0] = parseInt(amount[0]) + 1;
secondValue = 0;
}
}
}
if (secondValue.toString().length == 1) {
secondValue = "0" + secondValue;
}
result = parseFloat(amount[0] + "." + secondValue);
} else {
result = parseFloat(amount);
}
return result;
}