在 JavaScript 中使用两位小数格式化数字

编程入门 行业动态 更新时间:2024-10-24 09:20:51
本文介绍了在 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 中使用两位小数格式化数字

本文发布于:2023-11-10 06:16:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两位   小数   数字   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!