我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
这是整数。我如何返回两个小数点后的结果?
我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
这是整数。我如何返回两个小数点后的结果?
当前回答
要处理四舍五入到任何小数点后数位的问题,包含2行代码的函数就足以满足大多数需求。下面是一些示例代码。
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
其他回答
下面是一个工作示例
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
我认为我见过最好的方法是乘以10的位数次方,然后做个数学。四舍五入,最后除以10的数字次方。下面是我在typescript中使用的一个简单函数:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
或者纯javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
最快的方式-比toFixed()快:
两位小数
x = .123456
result = Math.round(x * 100) / 100 // result .12
三位小数
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
要得到两个小数的结果,你可以这样做:
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
要四舍五入的值乘以100以保留前两位数字,然后除以100以得到实际结果。
我找到的最好最简单的解决办法是
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01