1. 最笨的辦法
function get()
{ var s = 22.127456 + ""; var str = s.substring(0,s.indexOf(".") + 3);
alert(str);
}
2. 正則表達式效果不錯
< script type="text/javascript">onload = function(){ var a = "23.456322"; var aNew; var re = /([0-9]+.[0-9]{2})[0-9]*/;
aNew = a.replace(re,"$1");
alert(aNew);
}< /script>
3. 他就比較聰明了.....
< script>var num=22.127456;
alert( Math.round(num*100)/100);
< /script>
4.js保留2位小數(強制)
對于小數點位數大于2位的,用上面的函數沒問題,但是如果小于2位的,比如:changeTwoDecimal(3.1),將返回3.1,如果你一定需要3.10這樣的格式,那么需要下面的這個函數:
function changeTwoDecimal_f(x) { var f_x = parseFloat(x); if (isNaN(f_x)) {
alert('function:changeTwoDecimal->parameter error'); return false;
} var f_x = Math.round(x * 100) / 100; var s_x = f_x.toString(); var pos_decimal = s_x.indexOf('.'); if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
} while (s_x.length <= pos_decimal + 2) {
s_x += '0';
} return s_x;
}