这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
我想要10.80、2.40等数字。jQuery的使用对我来说很好。
这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
我想要10.80、2.40等数字。jQuery的使用对我来说很好。
当前回答
有一种方法可以100%确定你得到的数字有两个小数:
(Math.round(num*100)/100).toFixed(2)
如果这会导致舍入误差,你可以使用James在他的评论中解释的以下方法:
(Math.round((num * 1000)/10)/100).toFixed(2)
其他回答
我通常把它添加到我的个人库中,在一些建议和使用@TIMINeutron解决方案之后,并使其适用于十进制长度,这一个最适合:
function precise_round(num, decimals) {
var t = Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
将工作的例外报告。
将以下内容放在全局范围内:
Number.prototype.getDecimals = function ( decDigCount ) {
return this.toFixed(decDigCount);
}
然后试试:
var a = 56.23232323;
a.getDecimals(2); // will return 56.23
更新
请注意,toFixed()只能适用于0-20之间的小数,即a.g getdecimals(25)可能会生成一个javascript错误,所以为了适应,你可以添加一些额外的检查,即。
Number.prototype.getDecimals = function ( decDigCount ) {
return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
这很简单,和其他方法一样有效:
function parseNumber(val, decimalPlaces) {
if (decimalPlaces == null) decimalPlaces = 0
var ret = Number(val).toFixed(decimalPlaces)
return Number(ret)
}
由于toFixed()只能在数字上调用,并且不幸地返回一个字符串,因此它在两个方向上为您完成所有解析。你可以传递一个字符串或一个数字,每次你都会得到一个数字!调用parseNumber(1.49)将返回1,而调用parseNumber(1.49,2)将返回1.50。就像他们中最好的一样!
fun Any.twoDecimalPlaces(numInDouble: Double): String {
return "%.2f".format(numInDouble)
}
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
这对我很有用:在JavaScript中舍入小数