JavaScript / 내림, 올림, 반올림
자바스크립트에서 숫자를 내림할 때는 Math.floor(), 올림할 때는 Math.ceil(), 반올림할 때는 Math.round()를 사용합니다.
목차
Math.floor() - 내림
Math.floor()는 어떤 수보다 크지 않은 최대의 정수를 반환합니다.
문법
Math.floor( Number )
Number에는 숫자가 들어갑니다.
예제
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> </head> <body> <script> document.write( '<p>Math.floor( 1.4 ) : ' + Math.floor( 1.4 ) + '</p>' ); document.write( '<p>Math.floor( 1.5 ) : ' + Math.floor( 1.5 ) + '</p>' ); document.write( '<p>Math.floor( 1.6 ) : ' + Math.floor( 1.6 ) + '</p>' ); document.write( '<p>Math.floor( -1.4 ) : ' + Math.floor( -1.4 ) + '</p>' ); document.write( '<p>Math.floor( -1.5 ) : ' + Math.floor( -1.5 ) + '</p>' ); document.write( '<p>Math.floor( -1.6 ) : ' + Math.floor( -1.6 ) + '</p>' ); </script> </body> </html>
Math.ceil() - 올림
Math.ceil()는 어떤 수보다 작지 않은 최소의 정수를 반환합니다.
문법
Math.ceil( Number )
Number에는 숫자가 들어갑니다.
예제
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> </head> <body> <script> document.write( '<p>Math.ceil( 1.4 ) : ' + Math.ceil( 1.4 ) + '</p>' ); document.write( '<p>Math.ceil( 1.5 ) : ' + Math.ceil( 1.5 ) + '</p>' ); document.write( '<p>Math.ceil( 1.6 ) : ' + Math.ceil( 1.6 ) + '</p>' ); document.write( '<p>Math.ceil( -1.4 ) : ' + Math.ceil( -1.4 ) + '</p>' ); document.write( '<p>Math.ceil( -1.5 ) : ' + Math.ceil( -1.5 ) + '</p>' ); document.write( '<p>Math.ceil( -1.6 ) : ' + Math.ceil( -1.6 ) + '</p>' ); </script> </body> </html>
Math.round() - 반올림
Math.round()는 어떤 수와 가장 가까운 정수를 반환합니다. 어떤 수의 소수 부분이 0.5인 경우 가까운 큰 정수를 반환합니다.
문법
Math.round( Number )
Number에는 숫자가 들어갑니다.
예제
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> </head> <body> <script> document.write( '<p>Math.round( 1.4 ) : ' + Math.round( 1.4 ) + '</p>' ); document.write( '<p>Math.round( 1.5 ) : ' + Math.round( 1.5 ) + '</p>' ); document.write( '<p>Math.round( 1.6 ) : ' + Math.round( 1.6 ) + '</p>' ); document.write( '<p>Math.round( -1.4 ) : ' + Math.round( -1.4 ) + '</p>' ); document.write( '<p>Math.round( -1.5 ) : ' + Math.round( -1.5 ) + '</p>' ); document.write( '<p>Math.round( -1.6 ) : ' + Math.round( -1.6 ) + '</p>' ); </script> </body> </html>
내림, 올림, 반올림하는 자릿수 변경하기
Math.floor(), Math.ceil(), Math.round()는 정수로 만드는 것이므로, 소수 첫째 자리에서 내림, 올림, 반올림합니다. 만약 내림, 올림, 반올림하는 자릿수를 변경하고 싶다면 곱하기와 나누기를 이용합니다.
예를 들어 소수 둘째 자리에서 반올림하고 싶다면 10을 곱하여 반올림한 후 10으로 나눕니다.
Math.round( 1.25 * 10 ) / 10 // 1.3
백의 자리에서 반올림하고 싶다면 1000으로 나누고 반올림한 후 1000을 곱합니다.
Math.round( 1234567 / 1000 ) * 1000 // 1235000