在JavaScript中格式化一个正好两位小数的数字 [英] Formatting a number with exactly two decimals in JavaScript

查看:156
本文介绍了在JavaScript中格式化一个正好两位小数的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这行代码将我的数字四舍五入到小数点后两位。但是我得到这样的数字:10.8,2.4等等。这些不是我想要的两位小数,所以我如何改进以下内容?

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can improve the following?

Math.round(price*Math.pow(10,2))/Math.pow(10,2);

我想要10.80,2.40等数字。使用jQuery对我来说很好。

I want numbers like 10.80, 2.40, etc. Use of jQuery is fine with me.

推荐答案

要使用定点表示法格式化数字,只需使用 toFixed 方法:

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

请注意 toFixed()返回一个字符串。

Note that toFixed() returns a string.

重要:请注意,toFixed实际上没有圆,90%的时间,它会返回舍入值但在许多情况下,它实际上并不起作用。在你的控制台中试试这个:

IMPORTANT: Note that toFixed does not actually round, 90% of the time, it will return the rounded value but for many cases it doesn't actually work. Try this in your console:

2.005.toFixed(2)

你会得到错误的答案

在javascript中没有自然的方法来获得小数舍入,你需要自己的polyfill或使用库。你可以看看mozilla的polyfill这个 https:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

There is no natural way of getting a decimal rounding in javascript, you will need your own polyfill or use a library. You can look at mozilla's polyfill for this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

这篇关于在JavaScript中格式化一个正好两位小数的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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