JavaScript 中的数字舍入和截断。
JavaScript 中有两个函数分别用于数字舍入和截断:Math.round() 和 Math.trunc() −
- Math.round() − 将十进制数舍入到最接近的整数。
- Math.trunc() − 仅移除十进制数的小数部分,并将其转换为整数。
下面是 JavaScript 中数字舍入和截断的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result, .sample { font-size: 20px; font-weight: 500; color: blueviolet; } .sample { color: red; } </style> </head> <body> <h1>Rounding and truncating numbers in JavaScript</h1> <div class="sample">3.999</div> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Click on the above button to round and truncate the above number</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); BtnEle.addEventListener("click", () => { resEle.innerHTML = Math.round(3.9999) + "<br>"; resEle.innerHTML += Math.trunc(3.9999) + "<br>"; }); </script> </body> </html>
输出
点击‘点击此处’按钮 −
广告