这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的: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的使用对我来说很好。
当前回答
在这些例子中,当你试图四舍五入数字1.005时,你仍然会得到一个错误,解决方案是使用Math.js这样的库或这个函数:
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
其他回答
要使用定点表示法格式化一个数字,你可以简单地使用toFixed方法:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
注意,toFixed()返回一个字符串。
注意:toFixed在90%的情况下不会四舍五入,它会返回四舍五入的值,但在很多情况下,它不起作用。
例如:
2.005.toFixed(2) === "2.00"
更新:
现在,你可以使用国际电话。NumberFormat构造函数。它是ECMAScript国际化API规范(ECMA402)的一部分。它有很好的浏览器支持,甚至包括IE11,并且Node.js完全支持它。
const formatter = new Intl。NumberFormat(“en - us”{ minimumFractionDigits: 2 maximumFractionDigits: 2 }); console.log (formatter.format (2.005));/ /“2.01” console.log (formatter.format (1.345));/ /“1.35”
你也可以使用toLocaleString方法,它会在内部使用Intl API:
const format = (num, decimals) => num. tolocalestring ('en-US', { minimumFractionDigits: 2 maximumFractionDigits: 2 }); console.log(格式(2.005));/ /“2.01” console.log(格式(1.345));/ /“1.35”
这个API还为您提供了各种格式选项,如千个分隔符、货币符号等。
toFixed(n)提供小数点后的n个长度;toPrecision (x) 总长度为x。
使用下面的方法
// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
如果你想要固定的号码,可以使用
result = num.toFixed(2);
四舍五入您的十进制值,然后使用toFixed(x)为您期望的数字(s)。
function parseDecimalRoundAndFixed(num,dec){
var d = Math.pow(10,dec);
return (Math.round(num * d) / d).toFixed(dec);
}
Call
parseDecimalRoundAndFixed(10.800243929,4) => 10.80 parseDecimalRoundAndFixed(10.807243929,2) => 10.81
将以下内容放在全局范围内:
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);
}
在这些例子中,当你试图四舍五入数字1.005时,你仍然会得到一个错误,解决方案是使用Math.js这样的库或这个函数:
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}