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 中格式化正好有两位小数的数字


- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01