Javascript 取小数点后面N位
用Javascript取float型小数点后两位,例22.127456取成22.13,如何做?
1. 最笨的办法....... [我就怎么干的.........]
1
function get()
2
{
3
var s = 22.127456 + "";
4
var str = s.substring(0,s.indexOf(".") + 3);
5
alert(str);
6
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
2. 正则表达式效果不错
1
<script type="text/javascript">
2
onload = 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>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3. 他就比较聪明了.....
1
<script>
2
var num=22.127456;
3
alert( Math.round(num*100)/100);
4
</script>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4.会用新鲜东西的朋友....... 但是需要 IE5.5+才支持。
1
<script>
2
var num=22.127456;
3
alert( num.toFixed(2));
4
</script>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
转自:http://www.cnblogs.com/sqf/archive/2006/06/11/422980.html