티스토리 뷰출처 : https://okky.kr/article/350117 Show 보통은 이 방법들을 많이 쓴다.
그런데 나는 원하는 자리까지는 소수점을 보존하고 싶었다. substr 보다 더 신박한 방법이 있다고 한다.
원하는 소수점 자리만큼 10의 n승을 해서 곱해주고 (소수점 이하 5자리니까 * 100000) Math.floor로 소수점 이하를 버리고 아까 곱해준 만큼 다시 나눠줘서 소수로 되돌리는 방식입니다. Heojju카테고리 없음 [JavaScript] 소수점 올림 / 버림 / 반올림 / 자리수 표기우주별 2017. 8. 17. 13:33 ▤ 소수점 올림 <script> document.write(Math.ceil(123.456)+"\n"); //124 document.write(Math.ceil(123.567)+"\n"); //124 </script> ▤ 소수점 버림 <script> document.write(Math.floor(123.456)+"\n"); //124 document.write(Math.floor(123.567)+"\n"); //124 </script> ▤ 소수점 반올림 <script> document.write(Math.round(123.456)+"\n"); //123 document.write(Math.round(123.567)+"\n"); //124 </script> ▤ toFixed : 숫자를 문자열로 변환하면서 지정된 소수점 이하 숫자를 반올림하여 출력 <script> document.write((123.456).toFixed(0)+"\n"); //123 document.write((123.456).toFixed(2)+"\n"); //123.46 document.write((123.456).toFixed(4)+"\n"); //123.4560 document.write((123.789).toFixed(0)+"\n"); //124 document.write((123.789).toFixed(2)+"\n"); //123.79 document.write((123.789).toFixed(4)+"\n"); //123.7890 </script> ▤ toExponential : 숫자를 문자열로 변환하면서 소수점 앞의 숫자 하나와 지정된 개수의 소수점 이후 숫자로 구성되는 지수표기법을 사용하여 출력 <script> document.write((123.456).toExponential(0)+"\n"); //1e+2 document.write((123.456).toExponential(2)+"\n"); //1.23e+2 document.write((123.456).toExponential(4)+"\n"); //1.2346e+2 document.write((1234.56).toExponential(0)+"\n"); //1e+3 document.write((1234.56).toExponential(2)+"\n"); //1.23e+3 document.write((1234.56).toExponential(4)+"\n"); //1.2346e+3 </script> ▤ toPrecision : 지정된 수의 유효 숫자 개수만큼 숫자로 출력. 만약 유효 숫자 갯수가 숫자의 정수부분 전체를 출력할 만큼 충분하지 않다면 지수 표기법으로 출력 <script> document.write((123.456).toExponential(2)+"\n"); //1.23e+2 document.write((123.456).toExponential(4)+"\n"); //1.2346e+2 document.write((123.456).toExponential(7)+"\n"); //1.2345600e+2 </script> 참고 : http://fillin.tistory.com/88 웹 개발을 하다보면 다양한 요구사항이 생기기 마련입니다. 그 중에서도 아주 빈도가 높은 편은 아니지만 많이 요구되는 기능이 숫자 소수점 처리에 대한 것입니다. 보통 숫자를 표시하는 경우, 예를 들어 퍼센티지를 나타내는 등의 여러가지 지표를 보여줄 때 사용하게 됩니다. 이 번 포스팅에서는 자바스크립트에서 자바스크립트 소수점 자리수 처리 하는 방법자바스크립트에서 소수점을 처리하기 위해서 사용되는 함수는 다양하게 존재합니다. 가장 간단하면서 많은 사람들이 일반적으로 사용하는 방법은 빌트인 객체인
소수점 자리수 올림
소수점 자리수 내림
소수점 자리수 반올림
소수점 자리수 제거
소수점 자리수 제어 심화
특정 자리수에서 올림
특정 자리수에서 내림
참고 문서맺음이번 글에서는 간단하게 자바스크립트에서 소수점을 제어하는 다양한 방법들을 배워보았습니다. 혹시나 글에 이상한 점이 있다거나 궁금하신 점이 있으신 경우, 댓글 달아주시면 감사하겠습니다. Copied to clipboard |