在 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 round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.
例如:
2.005.toFixed(2) === "2.00"
现在,您可以使用 Intl.NumberFormat
构造函数.它是 ECMAScript 国际化 API 规范 (ECMA402) 的一部分.它有相当不错的浏览器支持,甚至包括IE11,它是Node.js 完全支持.
Nowadays, you can use the Intl.NumberFormat
constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"
您也可以使用 toLocaleString
方法,该方法在内部将使用 Intl
API:
You can alternatively use the toLocaleString
method, which internally will use the Intl
API:
const format = (num, decimals) => num.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(format(2.005)); // "2.01"
console.log(format(1.345)); // "1.35"
此 API 还为您提供了多种格式选项,例如千位分隔符、货币符号等.
This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.
相关文章