Home >Web Front-end >JS Tutorial >JavaScript gets the two decimal places after the decimal point of any float_javascript skills
用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); }