Round to at most 2 decimal places (only if necessa

2018-12-31 01:03发布

I'd like to round at most 2 decimal places, but only if necessary.

Input:

10
1.7777777
9.1

Output:

10
1.78
9.1

How can I do this in JavaScript?

30条回答
初与友歌
2楼-- · 2018-12-31 01:28

A simpler ES6 way is

const round = (x, n) => 
  parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n);

This pattern also returns the precision asked for.

ex:

round(44.7826456, 4)  // yields 44.7826
round(78.12, 4)       // yields 78.1200
查看更多
大哥的爱人
3楼-- · 2018-12-31 01:28

You can use

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57
查看更多
柔情千种
4楼-- · 2018-12-31 01:29
倾城一夜雪
5楼-- · 2018-12-31 01:29

If you are using lodash library, you can use the round method of lodash like following.

_.round(number, precision)

Eg:

_.round(1.7777777, 2) = 1.78
查看更多
何处买醉
6楼-- · 2018-12-31 01:30

Use this function Number(x).toFixed(2);

查看更多
查无此人
7楼-- · 2018-12-31 01:30

You should use:

Math.round( num * 100 + Number.EPSILON ) / 100

No one seems to be aware of Number.EPSILON.

Also it's worth noting that this is not a JavaScript weirdness like some people stated.

That is simply the way floating point numbers works in a computer. Like 99% of programming languages, JavaScript doesn't have home made floating point numbers; it relies on the CPU/FPU for that. A computer uses binary, and in binary, there isn't any numbers like 0.1, but a mere binary approximation for that. Why? For the same reason than 1/3 cannot be written in decimal: its value is 0.33333333... with an infinity of threes.

Here come Number.EPSILON. That number is the difference between 1 and the next number existing in the double precision floating point numbers. That's it: There is no number between 1 and 1 + Number.EPSILON.

EDIT:

As asked in the comments, let's clarify one thing: adding Number.EPSILON is relevant only when the value to round is the result of an arithmetic operation, as it can swallow some floating point error delta.

It's not useful when the value comes from a direct source (e.g.: literal, user input or sensor).

查看更多
登录 后发表回答