Home > Web Front-end > JS Tutorial > body text

JavaScript gets the two decimal places after the decimal point of any float_javascript skills

WBOY
Release: 2016-05-16 16:42:44
Original
1614 people have browsed it

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

1.这种方法最不推荐:

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

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); 
}
Copy after login


3. 比较高级的应用:

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

4. 最简单也最方便的:

function get(){ 
var num = new Number(13.37); 
num = num.toFixed(2);//2为要获取小数后的位数 会自动四舍五入 
alert(num); 
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template