📜  JavaScript Math round()方法(1)

📅  最后修改于: 2023-12-03 15:31:37.855000             🧑  作者: Mango

JavaScript Math round()方法

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() 方法遵循标准的四舍五入规则:

  • 如果小数部分 >= 0.5,向上舍入;
  • 如果小数部分 < 0.5,向下舍入。
兼容性

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
参考资料