toFixed()
是 JavaScript 中用于格式化数字的方法,它可以将数字转换为字符串,并保留指定的小数位数。该方法常用于处理货币、百分比等需要固定小数位数的场景。
语法
number.toFixed(digits)
number
: 要格式化的数字。digits
: 可选参数,表示要保留的小数位数,取值范围为0
到20
(包括0
和20
)。如果省略该参数,默认为0
。
返回值
toFixed()
返回一个字符串,表示格式化后的数字。
示例
-
保留两位小数
let num = 123.456; let result = num.toFixed(2); console.log(result); // 输出: "123.46"
-
保留整数(无小数)
let num = 123.456; let result = num.toFixed(); console.log(result); // 输出: "123"
-
保留更多小数位数
let num = 123.456; let result = num.toFixed(4); console.log(result); // 输出: "123.4560"
-
处理四舍五入
let num = 123.456789; let result = num.toFixed(3); console.log(result); // 输出: "123.457"
-
处理负数
let num = -123.456; let result = num.toFixed(2); console.log(result); // 输出: "-123.46"
注意事项
- 四舍五入:
toFixed()
会对数字进行四舍五入。例如,0.456.toFixed(2)
会返回"0.46"
。 - 返回值类型:
toFixed()
返回的是字符串,而不是数字。如果需要将其转换回数字,可以使用parseFloat()
或Number()
。 - 超出范围: 如果
digits
参数超出0
到20
的范围,会抛出RangeError
异常。
示例:将结果转换回数字
let num = 123.456;
let result = num.toFixed(2);
let numResult = parseFloat(result);
console.log(numResult); // 输出: 123.46
总结
toFixed()
是一个非常有用的方法,特别适合需要固定小数位数的场景。使用时需要注意其返回的是字符串,并且会对数字进行四舍五入处理。