Formatting a number with exactly two decimals in JavaScript(在 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.
这篇关于在 JavaScript 中格式化正好有两位小数的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中格式化正好有两位小数的数字


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01