如何将javascript中的数字格式化为两位小数?

如何将javascript中的数字格式化为两位小数?

问题描述:

我需要在javascript中将数字格式化为两位小数。为了做到这一点,我使用toFixed方法,它正常工作。

I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.

但是在数字没有任何小数位的情况下,它不应该显示小数点

But in cases, where numbers don't have any decimal digits, it should not show decimal point

例如10.00应该只有10而不是10.00。

e.g. 10.00 should be 10 only and not 10.00.

.toFixed()将结果转换为字符串

所以您需要将其转换为数字: jsBin演示

.toFixed() converts your result to String,
so you need to make it back a Number: jsBin demo

parseFloat( num.toFixed(2) )

或者只需使用一元 +

or by simply using the Unary +

+num.toFixed(2)

两者都将提供以下内容

//   15.00   --->   15
//   15.20   --->   15.2

如果你只想摆脱 .00 case,比你可以使用进行字符串操作.replace()

If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()

num.toFixed(2).replace('.00', '');

注意:以上内容将转换您的数字字符串

Note: the above will convert your Number to String.