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

One can use .toFixed(NumberOfDecimalPlaces).

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 01:24

One way to achieve such a rounding only if necessary is to use Number.prototype.toLocaleString():

myNumber.toLocaleString('en', {maximumFractionDigits:2, useGrouping:false})

This will provide exactly the output you expect, but as strings. You can still convert those back to numbers if that's not the data type you expect.

查看更多
听够珍惜
4楼-- · 2018-12-31 01:26

This may help you:

var result = (Math.round(input*100)/100);

for more information, you can have a look at this link

Math.round(num) vs num.toFixed(0) and browser inconsistencies

查看更多
永恒的永恒
5楼-- · 2018-12-31 01:26

None of the answers found here is correct. @stinkycheeseman asked to round up, you all rounded the number.

To round up, use this:

Math.ceil(num * 100)/100;
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 01:26

2017
Just use native code .toFixed()

number = 1.2345;
number.toFixed(2) // "1.23"

If you need to be strict and add digits just if needed it can use replace

number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');
查看更多
孤独寂梦人
7楼-- · 2018-12-31 01:27

Here is a simple way to do it:

Math.round(value * 100) / 100

You might want to go ahead and make a separate function to do it for you though:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

Then you would simply pass in the value.

You could enhance it to round to any arbitrary number of decimals by adding a second parameter.

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}
查看更多
登录 后发表回答