Home >Web Front-end >JS Tutorial >Tutorial on how to get two decimal places in js
本文主要和大家分享js如何取小数点后两位方法,Javascript取float型小数点后两位,例22.123456取成22.12,如何做?
1.通过substring截取。
function getnum() { var num = 22.123456; var result = num.substring(0,s.indexOf(".")+3); alert(result); }
2. 正则表达式。
function getnum() { var num = 22.123456; var aNew; var re = /([0-9]+\.[0-9]{2})[0-9]*/; aNew = num.replace(re,"$1"); alert(aNew); }
3.数据类型保留上。
function getnum() { var num=22.123456; alert( Math.round(num*100)/100); }
4.toFixed方法
alert(num.toFixed(2));
相关推荐:
The above is the detailed content of Tutorial on how to get two decimal places in js. For more information, please follow other related articles on the PHP Chinese website!