这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的: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);
}

其他回答

将以下内容放在全局范围内:

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);
}

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);

您还可以使用. toprecision()方法和一些自定义代码,无论int部分的长度如何,始终四舍五入到十进制第n位。

function glbfrmt (number, decimals, seperator) {
    return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}

你也可以让它成为一个插件,以便更好地使用。

我发现了一个非常简单的方法来解决这个问题,可以使用或适应:

td[row].innerHTML = price.toPrecision(price.toFixed(decimals).length

parse = function (data) { data = Math.round(data*Math.pow(10,2))/Math.pow(10,2); if (data != null) { var lastone = data.toString().split('').pop(); if (lastone != '.') { data = parseFloat(data); } } return data; }; $('#result').html(parse(200)); // output 200 $('#result1').html(parse(200.1)); // output 200.1 $('#result2').html(parse(200.10)); // output 200.1 $('#result3').html(parse(200.109)); // output 200.11 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="result"></div> <div id="result1"></div> <div id="result2"></div> <div id="result3"></div>