在 JavaScript 中将数字四舍五入到 2 个小数位

在 JavaScript 中将数字四舍五入到 2 个小数位

Round a Number to 2 Decimal Places in JavaScript

使用该toFixed()方法将数字四舍五入到小数点后两位,例如
const result = num.toFixed(2). toFixed方法会将数字四舍五入并将其格式化为小数点后两位。

索引.js
// ✅ round number to 2 decimal places const num1 = 13.5748; const result1 = num1.toFixed(2); console.log(result1); // 👉️ 13.57 console.log(typeof result1); // 👉️ string // 👇️ if you need to convert str to float const final = parseFloat(result1); console.log(final); // 👉️ 13.57 // ---------------------------------------- // ✅ round number wrapped in string to 2 decimal places // 👇️ if the value is a string // call parseFloat to convert it to a number first const str1 = '13.5758'; const result2 = parseFloat(str1).toFixed(2); console.log(result2); // 👉️ 13.58 console.log(typeof result2); // 👉️ string // ---------------------------------------- // 👇️ Convert string back to a number const num2 = 13.1999; const result3 = Number(num2.toFixed(2)); console.log(result3); // 👉️ 13.2 console.log(typeof result3); // 👉️ number

第一个示例使用
Number.toFixed
方法将数字四舍五入到小数点后两位。

索引.js
const num1 = 13.5748; const result1 = num1.toFixed(2); console.log(result1); // 👉️ 13.57 console.log(typeof result1); // 👉️ string // 👇️ if you need to convert str to float const final = parseFloat(result1); console.log(final); // 👉️ 13.57

该方法采用的唯一参数是小数点后出现的位数。

toFixed方法返回数字的字符串表示形式。

在第二个示例中,我们有一个包含在字符串中的浮点数。

索引.js
const str1 = '13.5758'; const result2 = parseFloat(str1).toFixed(2); console.log(result2); // 👉️ 13.58 console.log(typeof result2); // 👉️ string // 👇️ if you need to convert str to float const final = parseFloat(result2); console.log(final); // 👉️ 13.58

We used the
parseFloat
function to convert the string to a number because toFixed can only be called
on numbers.

You can use the Number object or the parseFloat() function to convert the
string that the toFixed method returns into a floating-point number.

index.js
const num2 = 13.1999; const result3 = Number(num2.toFixed(2)); console.log(result3); // 👉️ 13.2 console.log(typeof result3); // 👉️ number const final = parseFloat(num2.toFixed(2)); console.log(final); // 👉️ 13.2
However, notice that the trailing zero was removed after the conversion. This happens because JavaScript doesn’t keep insignificant trailing zeros around.

The number 1.00 is the same as 1, so the trailing zeros get dropped when the
value is converted to a number.

Note that floating-point numbers don’t represent all decimals precisely in
binary, which can lead to inconsistent results.

index.js
console.log(0.1 + 0.2 === 0.3); // 👉️ false const n1 = (13.555).toFixed(2); console.log(n1); // 👉️ 13.55 const n2 = (13.5551).toFixed(2); console.log(n2); // 👉️ 13.56

在第一个示例中0.1+0.2等于0.30000000000000004而不是
0.3. 这是因为二进制浮点格式不能准确表示0.1或之类的数字0.2

代码四舍五入到最接近的数字,导致四舍五入错误。

在第二个示例中,我们希望13.56返回,但数字却四舍五入为13.55.