我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
这是整数。我如何返回两个小数点后的结果?
我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
这是整数。我如何返回两个小数点后的结果?
当前回答
尝试使用discount.toFixed(2);
其他回答
下面是一个工作示例
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
如果使用一元加号将字符串转换为MDN上记录的数字。
例如:+ discount.toFixed (2)
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
尝试使用discount.toFixed(2);
要处理四舍五入到任何小数点后数位的问题,包含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;
}