Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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>

출력

JavaScript에서 숫자 반올림 및 자르기.

'여기를 클릭' 버튼을 클릭하면 -

JavaScript에서 숫자 반올림 및 자르기.