Javascript rounding result of splitting

I perform the following operation in Javascript:

0.0030 / 0.031

How can I round a result to an arbitrary number of places? What is the maximum number?

+3
source share
3 answers

Modern browsers must support a method called toFixed(). Here is an example taken from the Internet :

// 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() may also be useful to you, there is another great example on this page.


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

  • 10 ^ x (10 x), x .
    • Math.round()
    • 10 ^ x

, 5.11111111 , :

var result=Math.round(5.111111*1000)/1000  //returns 5.111
+13

1.7976931348623157 * 10 308. ECMAScript-262 3- . Number.MAX_VALUE, .

+2

Jag:

  • toFixed(). ; , .
  • , , . , , . - 1/3, , .
+1

Source: https://habr.com/ru/post/1716737/


All Articles