在 JavaScript 中使用两位小数格式化数字 [英] Formatting a number with exactly two decimals in JavaScript

查看:34
本文介绍了在 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 中使用两位小数格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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