这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的: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的使用对我来说很好。
当前回答
将以下内容放在全局范围内:
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);
}
其他回答
通过引用使用此响应:https://stackoverflow.com/a/21029698/454827
我建立了一个函数来获得动态的小数数:
function toDec(num, dec)
{
if(typeof dec=='undefined' || dec<0)
dec = 2;
var tmp = dec + 1;
for(var i=1; i<=tmp; i++)
num = num * 10;
num = num / 10;
num = Math.round(num);
for(var i=1; i<=dec; i++)
num = num / 10;
num = num.toFixed(dec);
return num;
}
这里的工作示例:https://jsfiddle.net/wpxLduLc/
这是我的1行解决方案:Number((yourNumericValueHere).toFixed(2));
事情是这样的:
1)首先,你将. tofixed(2)应用到你想要四舍五入的小数上。注意,这将把值从number转换为字符串。所以如果你使用Typescript,它会抛出一个这样的错误:
" string类型不能赋值给number类型"
2)要返回数值或将字符串转换为数值,只需对所谓的“字符串”值应用Number()函数。
为了说明问题,请看下面的例子:
例子: 我有一个金额,有高达5位小数,我想缩短到2位小数。我是这样做的:
Var价格= 0.26453; var priceround = Number((价格).toFixed(2)); console.log('原始价格:' +价格); console.log('价格四舍五入:' + pricerounds);
Number(((Math.random() * 100) + 1).toFixed(2))
这将返回一个从1到100四舍五入到小数点后2位的随机数。
一轮下来
function round_down(value, decPlaces) {
return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
围捕
function round_up(value, decPlaces) {
return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
圆的
function round_nearest(value, decPlaces) {
return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
合并https://stackoverflow.com/a/7641824/1889449和 https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm谢谢 他们。
又快又简单
parseFloat(number.toFixed(2))
例子
let number = 2.55435930
let roundedString = number.toFixed(2) // "2.55"
let twoDecimalsNumber = parseFloat(roundedString) // 2.55
let directly = parseFloat(number.toFixed(2)) // 2.55