나만의 작은 코딩

[Javascript] Math.ceil() vs Math.round() vs toFixed() 본문

Javascript

[Javascript] Math.ceil() vs Math.round() vs toFixed()

나작코 2023. 4. 25. 21:08

Math.ceil(), Math.round(), toFixed() 

 

- Math.ceil()

항상 올림하여 주어진 숫자보다 크거나 같은 더 작은 정수를 반환

console.log(Math.ceil(.95));
// Expected output: 1

console.log(Math.ceil(4));
// Expected output: 4

console.log(Math.ceil(7.004));
// Expected output: 8

console.log(Math.ceil(-7.004));
// Expected output: -7

참고 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cei

 

Math.ceil() - JavaScript | MDN

The Math.ceil() static method always rounds up and returns the smaller integer greater than or equal to a given number.

developer.mozilla.org

- Math.round()

가장 가까운 정수로 반올림한 숫자 값을 반환

console.log(Math.round(0.9));
// Expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// Expected output: 6 6 5

console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// Expected output: -5 -5 -6

참고 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

 

Math.round() - JavaScript | MDN

The Math.round() static method returns the value of a number rounded to the nearest integer.

developer.mozilla.org

- toFixed()

숫자를 고정 소수점 표기법(fixed-point nontation)으로 표시

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial('1.23e+5'));
// Expected output: "123000.00"
numObj.toFixed([digits])

- digits : 소수점 복귀 자릿수. 0이상 20이하의 값을 사용할 수 있으며, 구현체에 따라 더 넓은 범위의 값을 유지할 수 있음.

값을 지우지 않으면 0을 사용

참고: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

 

Number.prototype.toFixed() - JavaScript | MDN

toFixed() 메서드는 숫자를 고정 소수점 표기법(fixed-point notation)으로 표시합니다.

developer.mozilla.org

Math.ceil() vs Math.round()

Math.ceil()은 항상 소수점을 올려주는 올림법.

Math.round()는 소수점에 따라 올리거나 내리는 반올림법.

 

Math.ceil(), Math.round() vs toFixed()

toFixed()는 지정한 소수점 복귀 자리수까지 반올림해주기 때문에 정교한 계산이 필요할 때 용이.