javascript/문법 공부

[JS] 자릿수 ceil(), round(), floor()

늦깍이 2022. 5. 14. 19:55

Math.ceil()  -  올림

let a = 10;
a = Math.ceil(a / 3);
return a;

a는 4가 출력된다. 3.333333의 올림이니까!


Math.round() - 반올림

let a = 10;
a = Math.round(a / 3);
return a;

a는 3이 출력된다. 3.33333의 반올림이니까!


Math.floor() - 내림

let a = 10;
a = Math.floor(a / 3);
return a;

a는 3이 출력된다. 3.33333의 내림이니까!


소숫점의 경우

//function(변수 * 소숫점 자릿수) / 소숫점 자릿수
let a = 10.66666;
const ceil = Math.ceil(a * 10) / 10; // ceil = 10.7
const ceil = Math.ceil(a * 10) / 10; // ceil = 10.67
const round = Math.round(a * 10) / 10; // round = 10.7
const round = Math.round(a * 100) / 100; // round = 10.67
const floor = Math.floor(a * 10) / 10; // floor = 10.6
const floor = Math.floor(a * 100) / 100; // floor = 10.66

※소수점 숫자 정밀도 문제는 다음에 알아보도록 하자.