JavaScript gets the decimal number of any float to two decimal places

  • 2020-03-30 03:28:05
  • OfStack

Using Javascript to get a float to two decimal places, for example 22.127456 to 22.13, how to do?

1. Least recommended:


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

2. Use regular expressions to get:


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. Advanced applications:


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

The simplest and most convenient:


function get(){ 
var num = new Number(13.37); 
num = num.toFixed(2);//2 is automatically rounded to get the number of digits after the decimal
alert(num); 
}

Related articles: