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   longlinji  阅读(1690)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示