round value to 2 decimals javascript

核能气质少年 提交于 2019-12-30 01:47:29

问题


I have a small issue with the final value, i need to round to 2 decimals.

var pri='#price'+$(this).attr('id').substr(len-2);
            $.get("sale/price?output=json", { code: v },
               function(data){
                 $(pri).val(Math.round((data / 1.19),2));
            });
        });

Any help is appreciated.

Solution: $(pri).val(Math.round((data / 1.19 * 100 )) / 100);


回答1:


Just multiply the number by 100, round, and divide the resulting number by 100.




回答2:


If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)



来源:https://stackoverflow.com/questions/14666752/round-value-to-2-decimals-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!