`
v11159588
  • 浏览: 2267 次
  • 性别: Icon_minigender_1
  • 来自: 安康
最近访客 更多访客>>
社区版块
存档分类
最新评论

小数点后多位

    博客分类:
  • java
 
阅读更多
public class CalcFrac {
02     public static void printFraction(double a, double b, int fracLen) {
03         //处理负数
04         boolean isNegative = false;
05         if(a / b < 0) {
06             isNegative = true;
07             a = a < 0 ? -a : a;
08             b = b < 0 ? -b : b;
09         }
10         //计算小数
11         StringBuilder builder = null;
12         for(int i = 0; i < fracLen; ++i) {
13             double frac = a % b;
14             int num = (int)(a/b);
15             if(builder == null) {
16                 //初始化
17                 builder = new StringBuilder();
18                 //负数时添加负号
19                 if(isNegative) {
20                     builder.append("-");
21                 }
22                 //添加整数部分和小数点
23                 builder.append(num).append(".");               
24             else {
25                 //添加小数部分
26                 builder.append(num);
27             }
28             a = frac * 10;
29         }
30         System.out.println(builder.toString());
31     }
32  
33     public static void main(String[] args) {
34         int a = 1, b = 3;
35         if(args.length >= 2) {
36             //从命里行获取数字
37             a = Integer.valueOf(args[0]);
38             b = Integer.valueOf(args[1]);
39         }
40         printFraction(a,b,1000);
41     }
42 }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics