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:07

To not deal with many 0s, use this variant:

Math.round(num * 1e2) / 1e2
查看更多
还给你的自由
3楼-- · 2018-12-31 01:07

MarkG and Lavamantis offered a much better solution than the one that has been accepted. It's a shame they don't get more upvotes!

Here is the function I use to solve the floating point decimals issues also based on MDN. It is even more generic (but less concise) than Lavamantis's solution:

function round(value, exp) {
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp  = +exp;

  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

Use it with:

round(10.8034, 2);      // Returns 10.8
round(1.275, 2);        // Returns 1.28
round(1.27499, 2);      // Returns 1.27
round(1.2345678e+2, 2); // Returns 123.46

Compared to Lavamantis's solution, we can do...

round(1234.5678, -2); // Returns 1200
round("123.45");      // Returns 123
查看更多
有味是清欢
4楼-- · 2018-12-31 01:08

Use Math.round(num * 100) / 100

查看更多
冷夜・残月
5楼-- · 2018-12-31 01:09

Use something like this "parseFloat(parseFloat(value).toFixed(2))"

parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78 
parseFloat(parseFloat("10").toFixed(2))-->10 
parseFloat(parseFloat("9.1").toFixed(2))-->9.1
查看更多
临风纵饮
6楼-- · 2018-12-31 01:09

There are a couple of ways to do that. For people like me, the Lodash's variant

function round(number, precision) {
    var pair = (number + 'e').split('e')
    var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
    pair = (value + 'e').split('e')
    return +(pair[0] + 'e' + (+pair[1] - precision))
}

Usage:

round(0.015, 2) // 0.02
round(1.005, 2) // 1.01

If your project uses jQuery or lodash, you can also find proper round method in the libraries.

Update 1

I removed the variant n.toFixed(2), because it is not correct. Thank you @avalanche1

查看更多
春风洒进眼中
7楼-- · 2018-12-31 01:10

Here is a prototype method:

Number.prototype.round = function(places){
    places = Math.pow(10, places); 
    return Math.round(this * places)/places;
}

var yournum = 10.55555;
yournum = yournum.round(2);
查看更多
登录 后发表回答