// 四舍五入的实现方法
// 使用 Math.round() 方法
let num1 = 4.5;
let roundedNum1 = Math.round(num1);
console.log(roundedNum1); // 输出: 5
// 对小数进行四舍五入
let num2 = 4.4;
let roundedNum2 = Math.round(num2);
console.log(roundedNum2); // 输出: 4
// 如果需要对特定小数位进行四舍五入,可以使用 toFixed() 方法
let num3 = 12.3456;
let roundedNum3 = parseFloat(num3.toFixed(2));
console.log(roundedNum3); // 输出: 12.35
// 解释:
// Math.round() 是 JavaScript 内置的四舍五入函数,它会将数字四舍五入到最接近的整数。
// toFixed(n) 方法用于将数字格式化为指定小数位数的字符串,并返回该字符串。使用 parseFloat() 可以将其转换回数字。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站