在 JavaScript 中,可以使用 toFixed
方法来保留尾随零。 toFixed
方法将数字四舍五入为指定小数位数,并将结果作为字符串返回。
以下是一个示例代码:
let num = 10.00;
console.log(num.toFixed(2)); // 输出 "10.00"
在上面的示例中,使用 toFixed
方法将数字 10.00
转换为字符串 "10.00"
,并保留了尾随的零。
请注意,toFixed
方法将返回一个字符串,而不是一个数字。如果需要执行数学运算,可以使用 parseFloat
或 Number
函数将字符串转换回数字。
let num = 10.00;
let numWithZero = num.toFixed(2); // 返回一个字符串
console.log(parseFloat(numWithZero)); // 输出 10
console.log(Number(numWithZero)); // 输出 10
上面的代码将字符串 "10.00"
转换回数字 10
。