js除法四舍五入

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
 2 <html>    
 3 <head>  
 4 <title>floatDecimal.html</title>  
 5 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">      
 6 <meta http-equiv="description" content="this is my page">  
 7 <meta http-equiv="content-type" content="text/html; charset=UTF-8">   
 8 <script type="text/javascript">   
 9 //保留两位小数    
10 //功能:将浮点数四舍五入,取小数点后2位     
11 function toDecimal(x) {   
12   var f = parseFloat(x);    
13 if (isNaN(f)) {   
14   return;    
15 }          
16 f = Math.round(x*100)/100;  
17 return f;        
18 }       
19 //制保留2位小数,如:2,会在2后面补上00.即2.00          
20 
21 function toDecimal2(x) {
22 var f = parseFloat(x);      
23 if (isNaN(f)) {   
24  return false;     
25 }          
26 var f = Math.round(x*100)/100;  
27 var s = f.toString();       
28 var rs = s.indexOf('.');      
29 if (rs < 0) {   
30  rs = s.length;      
31  s += '.';   
32             }       
33 while (s.length <= rs + 2) {   
34  s += '0';       
35 }            
36 return s;   
37 }                     
38 
39 function fomatFloat(src,pos){      
40              return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);     
41 }          
42 
43 //四舍五入   
44 alert("保留2位小数:" + toDecimal(3.14159267));  
45 alert("强制保留2位小数:" + toDecimal2(3.14159267));
46 alert("保留2位小数:" + toDecimal(3.14559267));   
47 alert("强制保留2位小数:" + toDecimal2(3.15159267));   
48 alert("保留2位小数:" + fomatFloat(3.14559267, 2));
49 alert("保留1位小数:" + fomatFloat(3.15159267, 1));   
50 //五舍六入    
51 alert("保留2位小数:" + 1000.003.toFixed(2));          
52 alert("保留1位小数:" + 1000.08.toFixed(1));   
53 alert("保留1位小数:" + 1000.04.toFixed(1));     
54 alert("保留1位小数:" + 1000.05.toFixed(1));    
55 //科学计数  
56 alert(3.1415.toExponential(2));      
57 alert(3.1455.toExponential(2));   
58 alert(3.1445.toExponential(2));  
59 alert(3.1465.toExponential(2));  
60 alert(3.1665.toExponential(1));   
61 //精确到n位,不含n位      
62 alert("精确到小数点第2位" + 3.1415.toPrecision(2));   
63 alert("精确到小数点第3位" + 3.1465.toPrecision(3));  
64 alert("精确到小数点第2位" + 3.1415.toPrecision(2));  
65 alert("精确到小数点第2位" + 3.1455.toPrecision(2));    
66 alert("精确到小数点第5位" + 3.141592679287.toPrecision(5));      
67 </script>    
68 </head>
69 <body>
70 This is my HTML page. <br>   
71 </body> 
72 </html>
View Code

 

posted on 2018-10-26 16:21  longlinji  阅读(1688)  评论(0编辑  收藏  举报