Home > Web Front-end > JS Tutorial > JavaScript gets the two decimal places after the decimal point of any float_javascript skills

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:42:44
Original
1688 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:
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
Latest Issues
Why not float?
From 1970-01-01 08:00:00
0
0
0
Float a div inside another div
From 1970-01-01 08:00:00
0
0
0
php json_decode float loses decimal point
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template