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>輸出

點選‘點選此處’按鈕 −

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP