DEV/JavaScript
javascript util
초록매실원액
2015. 12. 17. 15:56
자바스크립트 int계산
1 2 3 4 | var a = 10; var b = 20; a + b; //1020 parseInt(a) + parseInt(b); //30 |
1. 소수점 올림, 버림, 반올림
Math.ceil() : 소수점 올림, 정수형 반환
Math.floor() : 소수점 버림, 정수형 반환
Math.round() : 소수점 반올림, 정수형 반환
var n = 123.456;
alert(Math.ceil(n)); // 124
alert(Math.round(n)); // 123
n = 123.567;
alert(Math.ceil(n)); // 124
alert(Math.floor(n)); // 123
alert(Math.round(n)); // 124
2. 소수점 자리수 표기
toFiexed() : 숫자를 문자열로 변환하면서 지정된 소수점 이하 숫자를 반올림하여 출력한다.
toExponential() : 숫자를 문자열로 변환하면서 소수점 앞의 숫자 하나와 지정된 개수의 소수점 이후 숫자로 구성되는 지수표기법을 사용하여 출력한다.
toPrecision() : 지정된 수의 유효 숫자 개수만큼 숫자로 출력한다. 만약 유효 숫자 갯수가 숫자의 정수부분 전체를 출력할 만큼 충분하지 않으면 지수 표기법으로 출력된다.
위 세 가지 Method는 모두 반올림하여 출력된다.
var n = 123.456;
alert(n.toFixed(0)); // 123
alert(n.toFixed(2)); // 123.46
alert(n.toExponential(1)); // 1.2e+2
alert(n.toExponential(3)); // 1.235e+2
alert(n.toPrecision(2)); // 1.2e+2
alert(n.toPrecision(4)); // 123.5
alert(n.toPrecision(7)); // 123.4560
3. 원단위 절사
원단위의 경우 10, 십원단위의 경우 100, 백원단위의 경우 1000, ... 을 이용하면 원단위 절사가 가능하다.
var n = 2117;
n = Math.floor(n/10) * 10; // 10으로 나누면 211.7, floor 함수로 소수점을 버리면 211, 다시 10을 곱하면 2110
alert(n); // 2110
자바스크립트 숫자만 입력
1234567891011121314151617 $(function(){// 숫자 입력만 가능$(".onlynum").keypress( function (e) {var key = e.charCode || e.keyCode || 0;// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLYreturn (key == 3 || /* Ctrl+c */key == 22 || /* Ctrl+v */key == 8 ||key == 9 ||key == 46 ||(key >= 37 && key <= 40) ||(key >= 48 && key <= 57));// (key >= 96 && key <= 105));});cs
자바스크립트 천단위 콤마
1234567891011121314 function comma(num){ //천단위에 콤마var reg = /(^[+-]?\d+)(\d{3})/;num += '';while(reg.test(num)){num = num.replace(reg, '$1' + ',' + '$2');}return num;}function unNumberFormat(num) { //콤마 제거return (num.replace(/\,/g,""));}cs