toFixed()和toLocaleString()无法同时使用,最终结果不理想
toLocaleString()将数字转换为带千分位的字符串格式
toFixed(2) 将数字转化为保留两位小数的字符串格式
var number=123,456.899 没有保留2位小数
number.toLocaleString().toFixed(2) //123,456.899 没有保留2位小数
number.toFixed(2)r.toLocaleString() // 123,456.89 没有千分位
原因:以上两种方式,都在第一次转换时已经成为字符串了无法正确应用第二次转换
应该在toFix后将结果先转换为数字形式再调用toLocaleString
或使用正则:.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
注意:
toFixed的修约(舍入)规则并不是“四舍五入”,而是“四舍六入五成双”,也即“4舍6入5凑偶”。
这里“四”是指≤4 时舍去,"六"是指≥6时进上,"五"指的是根据5后面的数字来定,当5后有有效数字(不为0)时,舍5入1;当5后无有效数字时,需要分两种情况来讲:①5前为奇数,舍5入1;②5前为偶数,舍5不进。(0是偶数)
可以使用Math.round()将数字放大一定倍数后处理
function round(number, precision) {
return Math.round(+number + 'e' + precision) / Math.pow(10, precision);
}
round(1.235, 2) //1.24
round(1.355, 2) //1.36
