js保留两位小数最简单的6种方法
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在JavaScript中,要将数字保留两位小数,可以使用以下几种方法:
- 使用
toFixed()
方法:
let num = 123.456;
let fixedNum = num.toFixed(2); // "123.46" 返回字符串
- 使用
Math.round()
方法:
let num = 123.456;
let roundedNum = Math.round(num * 100) / 100; // 123.46
- 使用字符串模板:
let num = 123.456;
let strNum = `${num.toFixed(2)}`; // "123.46" 字符串
- 使用
Number()
和toFixed()
结合:
let num = 123.456;
let numFixed = Number(num.toFixed(2)); // 123.46 返回数字
- 使用
slice()
方法:
let num = 123.456;
let slicedNum = Number(num.toString().slice(0, num.toString().indexOf('.') + 3)); // 123.46
- 使用正则表达式:
let num = 123.456;
let regexNum = Number(num.toString().replace(/(\d+\.\d{2})\d+/, '$1')); // 123.46
以上每种方法都可以将数字保留两位小数,选择合适的方法根据实际需求使用。注意,toFixed()
方法返回的是字符串,如果需要得到数字类型的结果,可能需要额外处理。
评论已关闭