如何将javascript中的数字格式化为两位小数? [英] How to format numbers in javascript to two decimal digits?

查看:58
本文介绍了如何将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.

这篇关于如何将javascript中的数字格式化为两位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆