用Javascript取float型小数点后两位,例22.127456取成22.13,如何做?
1. 最笨的办法....... [我就怎么干的.........]
1function get()
2{
3 var s = 22.127456 + "";
4 var str = s.substring(0,s.indexOf(".") + 3);
5 alert(str);
6}
2{
3 var s = 22.127456 + "";
4 var str = s.substring(0,s.indexOf(".") + 3);
5 alert(str);
6}
2. 正则表达式效果不错
script type="text/javascript">
2onload = function(){
3 var a = "23.456322";
4 var aNew;
5 var re = /([0-9]+\.[0-9]{2})[0-9]*/;
6 aNew = a.replace(re,"$1");
7 alert(aNew);
8}
9</script>
2onload = function(){
3 var a = "23.456322";
4 var aNew;
5 var re = /([0-9]+\.[0-9]{2})[0-9]*/;
6 aNew = a.replace(re,"$1");
7 alert(aNew);
8}
9</script>
3. 他就比较聪明了.....
script>
2var num=22.127456;
3alert( Math.round(num*100)/100);
4</script>
2var num=22.127456;
3alert( Math.round(num*100)/100);
4</script>
4.会用新鲜东西的朋友....... 但是需要 IE5.5+才支持。
<script>
2var num=22.127456;
3alert( num.toFixed(2));
4</script>
2var num=22.127456;
3alert( num.toFixed(2));
4</script>