📅  最后修改于: 2023-12-03 15:31:37.855000             🧑  作者: Mango
Math.round()
方法用于将一个数字四舍五入到最接近的整数。
Math.round(x)
参数:
x
:必需。要进行四舍五入的数字。返回值:最接近参数 x
的整数。
Math.round(4.5) // 5
Math.round(4.49) // 4
Math.round(-4.5) // -4
Math.round(-4.49) // -4
Math.round()
方法遵循标准的四舍五入规则:
Math.round()
方法兼容所有浏览器,包括 IE6+。
const price1 = 12.34
const price2 = 56.78
const totalPrice = Math.round((price1 + price2) * 100) / 100
console.log(totalPrice) // 69.12
function roundDecimal(num, decimal) {
const base = Math.pow(10, decimal)
return Math.round(num * base) / base
}
console.log(roundDecimal(3.14159265359, 2)) // 3.14
console.log(roundDecimal(21.9764, 1)) // 22.0
console.log(roundDecimal(1234.5678, 0)) // 1235