Format number to always show 2 decimal places

2018-12-31 03:15发布

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

I have been using this:

parseFloat(num).toFixed(2);

But it's displaying 1 as 1, rather than 1.00.

26条回答
笑指拈花
2楼-- · 2018-12-31 03:29

For the most accurate rounding, create this function:

function round(value, decimals) {
    return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
}

and use it to round to 2 decimal places:

console.log("seeked to " + round(1.005, 2));
> 1.01

Thanks to Razu, this article, and MDN's Math.round reference.

查看更多
低头抚发
3楼-- · 2018-12-31 03:29

Is this what you mean?

function showAsFloat(num, n){
      return !isNaN(+num) ? (+num).toFixed(n || 2) : num;
}

document.querySelector('#result').textContent = 
    [
     'command                      | result',
     '-----------------------------------------------',
     'showAsFloat(1);              | ' + showAsFloat(1),
     'showAsFloat(1.314);          | ' + showAsFloat(1.314),
     'showAsFloat(\'notanumber\')    | ' + showAsFloat('notanumber'),
     'showAsFloat(\'23.44567\', 3)   | ' + showAsFloat('23.44567', 3),
     'showAsFloat(2456198, 5)      | ' + showAsFloat('2456198', 5),
     'showAsFloat(0);              | ' + showAsFloat(0)
    ].join('\n');
<pre id="result"></pre>

查看更多
ら面具成の殇う
4楼-- · 2018-12-31 03:30

I do like:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

查看更多
谁念西风独自凉
5楼-- · 2018-12-31 03:31

For modern browsers, use toLocaleString:

var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });

Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:

num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

which gives:

1.35

Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:

num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

it will give:

1,35

查看更多
永恒的永恒
6楼-- · 2018-12-31 03:32

This works fine in FF4:

parseFloat(Math.round(num3 * 100) / 100).toFixed(2);

Live Demo

var num1 = "1";
document.getElementById('num1').innerHTML = parseFloat(Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
document.getElementById('num2').innerHTML = parseFloat(Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
document.getElementById('num3').innerHTML = parseFloat(Math.round(num3 * 100) / 100).toFixed(2);
span {
    border: 1px solid #000;
    margin: 5px;
    padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>

Note that it will round to 2 decimal places, so the input 1.346 will return 1.35.

查看更多
梦寄多情
7楼-- · 2018-12-31 03:32

Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.

A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ

As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.

查看更多
登录 后发表回答