Rounding the result of division in Javascript

前端 未结 3 1323
南旧
南旧 2021-01-21 02:16

I\'m performing the following operation in Javascript:

0.0030 / 0.031

How can I round the result to an arbitrary number of places? W

相关标签:
3条回答
  • 2021-01-21 02:25

    The largest positive finite value of the number type is approximately 1.7976931348623157 * 10308. ECMAScript-262 3rd ed. also defines Number.MAX_VALUE which holds that value.

    0 讨论(0)
  • 2021-01-21 02:47

    To answer Jag's questions:

    1. Use the toFixed() method. Beware; it returns a string, not a number.
    2. Fifteen, maybe sixteen. If you try to get more, the extra digits will be either zeros or garbage. Try formatting something like 1/3 to see what I mean.
    0 讨论(0)
  • 2021-01-21 02:50

    Modern browsers should support a method called toFixed(). Here's an example taken from the web:

    // Example: toFixed(2) when the number has no decimal places
    // It will add trailing zeros
    var num = 10;
    var result = num.toFixed(2); // result will equal 10.00
    
    // Example: toFixed(3) when the number has decimal places
    // It will round to the thousandths place
    num = 930.9805;
    result = num.toFixed(3); // result will equal 930.981
    

    toPrecision() might also be useful for you, there is another excellent example on that page.


    For older browsers, you can achieve it manually using Math.round. Math.round() will round to the nearest integer. In order to achieve decimal precision, you need to manipulate your numbers a bit:

    1. Multiply the original number by 10^x (10 to the power of x), where x is the number of decimal places you want.
      • Apply Math.round()
      • Divide by 10^x

    So to round 5.11111111 to three decimal places, you would do this:

    var result=Math.round(5.111111*1000)/1000  //returns 5.111
    
    0 讨论(0)
提交回复
热议问题