Home  >  Article  >  Web Front-end  >  JS format number retaining two decimal points sample code_javascript skills

JS format number retaining two decimal points sample code_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:20:061525browse

Question: Multiple ways to format data in JS with functions retaining two decimal places

The best way:

It seems like this is how we keep two people

Copy code The code is as follows:

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

Description:

alert(Number.toFixed(9.39393));

The returned value is 9.39
But only versions above ie5.5 are supported.

Other methods:

function roundFun(numberRound,roundDigit) //四舍五入,保留位数为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:

Copy code The code is as follows:

var a=3.1415926;
a = a.toFixed(2);//Reserve 2 bits but the result is a String type
a = parseFloat(a);//Convert the result to float
//The words in one step are as follows
a = parseFloat(a.toFixed(2));
Statement:
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