js保留两位小数点(整数商品价格渲染时,保留后两位数)

解决方案: 使用toFixed

Number.toFixed(2)

 问题描述:想展示¥9.00到页面上,却只展示了¥9

代码:

var price = 9.00
document.write(price)

页面效果:

解决办法:使用toFixed(num) , 将数字转为指定小数点的字符串

JavaScript toFixed() 方法 | 菜鸟教程

var price = 9.00
document.write(price.toFixed(2))

页面效果:

补充说明:toFixed返回值是字符串,如果直接拿来进行数学运算,会出现字符串拼接的结果

如: 10.00.toFixed(2) + 10.45  ===》   '10.0010.45'

解决办法:

(1)再次转为数字

Number(10.00.toFixed(2)) + 10.45  ===>  20.45

猜你喜欢

转载自blog.csdn.net/A_Common_Man/article/details/126122564