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

This answer will fail if value = 1.005.

As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

Number(Math.round(1.005+'e2')+'e-2').toFixed(2); // 1.01

Credit: Rounding Decimals in JavaScript

查看更多
骚的不知所云
3楼-- · 2018-12-31 03:47

If you're already using jQuery, you could look at using the jQuery Number Format plugin.

The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.

$.number( 123, 2 ); // Returns '123.00'

You can also get jQuery Number Format from GitHub.

查看更多
登录 后发表回答