// 四舍五入的示例代码
// 使用 Math.round() 方法进行四舍五入
let num1 = 4.5;
let roundedNum1 = Math.round(num1);
console.log(roundedNum1); // 输出: 5
let num2 = 3.2;
let roundedNum2 = Math.round(num2);
console.log(roundedNum2); // 输出: 3
// 对小数点后多位进行四舍五入
function roundToDecimalPlaces(num, decimalPlaces) {
let factor = Math.pow(10, decimalPlaces);
return Math.round(num * factor) / factor;
}
let num3 = 3.14159;
let roundedNum3 = roundToDecimalPlaces(num3, 2);
console.log(roundedNum3); // 输出: 3.14
Math.round()
进行四舍五入,最后再除以相同的因子来恢复原始的小数位数。希望这些示例能帮助你理解如何在 JavaScript 中实现四舍五入。
上一篇:js 数字四舍五入
下一篇:js >>>
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站