round value to 2 decimals javascript

前端 未结 2 1140
面向向阳花
面向向阳花 2020-12-30 02:14

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/pri         


        
相关标签:
2条回答
  • 2020-12-30 02:35

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

    0 讨论(0)
  • 2020-12-30 02:50

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

    0 讨论(0)
提交回复
热议问题