Home  >  Article  >  Web Front-end  >  JavaScript 获取任一float型小数点后两位的小数_javascript技巧

JavaScript 获取任一float型小数点后两位的小数_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:42:441516browse

用Javascript取float型小数点后两位,例22.127456取成22.13,如何做?

1.这种方法最不推荐:

function get(){ 
var s = 22.127456 + ""; 
var str = s.substring(0,s.indexOf(".") + 3); 
alert(str); 
}

2. 使用正则表达式获取:

function get(){ 
var a = "23.456322"; 
var aNew; 
var re = /([0-9]+\.[0-9]{2})[0-9]*/; 
aNew = a.replace(re,"$1"); 
alert(aNew); 
}


3. 比较高级的应用:

function get(){ 
var num=22.127456; 
alert( Math.round(num*100)/100); 
}

4. 最简单也最方便的:

function get(){ 
var num = new Number(13.37); 
num = num.toFixed(2);//2为要获取小数后的位数 会自动四舍五入 
alert(num); 
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn