JS format Numbers to keep two decimal point sample code

  • 2020-03-26 21:23:59
  • OfStack

Problem: multiple ways to format a function in JS that preserves two decimal places in data

Best way:

Keep two of them, I think


var a = 9.39393;
alert(a.toFixed(2));

Description:

Alert (Number. ToFixed (9.39393));

Other methods:


function roundFun(numberRound,roundDigit) //Round to the roundDigit
 { 
 if (numberRound>=0) 
 { 
 var tempNumber = parseInt((numberRound * Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit); 
 return tempNumber; 
 } 
 else  
 { 
 numberRound1=-numberRound 
 var tempNumber = parseInt((numberRound1 * Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit); 
 return -tempNumber; 
 } 
}

Method 2:


<script> 
 tmp = "1234567.57232" 
 result = tmp.substr(0,tmp.indexOf(".")+3); 
 alert(result); 
 </script> 

Method 3:

 
var a=3.1415926;
a = a.toFixed(2);//Keep 2 bits but the result is a String type
a = parseFloat(a);//Converting the result will float
//In one step, I'll say
a = parseFloat(a.toFixed(2));


Related articles: