这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?

Math.round(price*Math.pow(10,2))/Math.pow(10,2);

我想要10.80、2.40等数字。jQuery的使用对我来说很好。


当前回答

(Math.round((10.2)*100)/100).toFixed(2)

结果应该是10.20

(Math.round((.05)*100)/100).toFixed(2)

结果应该是:0.05

(Math.round((4.04)*100)/100).toFixed(2)

结果应该是:4.04

etc.

其他回答

通过引用使用此响应: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/

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>

100%的工作! !试一试

<html> <head> <script> function replacePonto(){ var input = document.getElementById('qtd'); var ponto = input.value.split('.').length; var slash = input.value.split('-').length; if (ponto > 2) input.value=input.value.substr(0,(input.value.length)-1); if(slash > 2) input.value=input.value.substr(0,(input.value.length)-1); input.value=input.value.replace(/[^0-9.-]/,''); if (ponto ==2) input.value=input.value.substr(0,(input.value.indexOf('.')+3)); if(input.value == '.') input.value = ""; } </script> </head> <body> <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()"> </body> </html>

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

这对我很有用:在JavaScript中舍入小数

要使用定点表示法格式化一个数字,你可以简单地使用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还为您提供了各种格式选项,如千个分隔符、货币符号等。