【问题标题】:Best way to print 2 doubles with same exponent使用相同指数打印 2 个双打的最佳方法
【发布时间】:2015-04-16 13:35:56
【问题描述】:

如何最好地以科学计数法打印 2 个浮点数但具有相同的指数? 例如:我想打印这样的数字:

 1.234e-6 
11.234e-6

我想要一些函数来自动检测最佳指数 - 较小的数字总是从第一个十进制数字开始,较大的数字打印它必须如何使用相同的指数。 例如:0.1 和 100 将打印

   1.000e-1
1000.000e-1

但即使我明确要求两位小数 String.format("%2.3e",11.234e-6) 我得到了 1.123e-5

【问题讨论】:

    标签: java string double scientific-notation


    【解决方案1】:

    到目前为止,我想出了下面的代码。它按我的意愿工作。但正如您所看到的,它并不完全短或快......如果有人能指出一些 Java 原生函数来帮助我更优雅地完成它,那就太好了......

    public static String repeat(int count, String with) {
        if(count<0){
            return "";
        }
        if(count>1e5){
            return "";
        }
        return new String(new char[count]).replace("\0", with);
    }
    
    public static String getFormattedDouble(double num,int posInt,int posFrac){
        if(num == 0) return "0"; // correct 0 value to be print only with one 0
        String sInt = repeat(posInt,"0");
        String sFrac = repeat(posFrac,"0");
        String sSing = num<0 ? "" : "+";
        DecimalFormat form = new DecimalFormat(sSing+sInt+"."+sFrac+"E0");
        String s = form.format(num);
        s = s.replace("E","e"); // I really thing capital E looks ugly
        return s;
    }
    
    public static String[] get2doublesSameExp(double a, double b){
        String[] s = new String[2];
        int expA;
        if(a == 0) expA = 0;
        else       expA = (int)Math.floor(Math.log10(Math.abs(a)));
        int expB;
        if(b == 0) expB = 0;
        else       expB = (int)Math.floor(Math.log10(Math.abs(b)));
        double expDif = Math.abs((double)expA-(double)expB);
        int fractPos = 3;
        if(expDif > 4) fractPos = 1; // too big exponent difference reduce fraction digits
        if(expDif > 6){
            // too big exponent difference print it normally it will be nicer
            s[0] = String.format("%1.3e",a);
            s[1] = String.format("%1.3e",b);
            return s;
        }
        int minExp = Math.min(expA,expB) - 1;
        s[0] = getFormattedDouble(a, expA - minExp, fractPos );
        s[1] = getFormattedDouble(b, expB - minExp, fractPos );
        // just text right justification
        String rightJust = repeat((int)expDif," ");
        int justIdx = expA < expB ? 0 : 1;
        s[justIdx] = rightJust + s[justIdx];
        return s;
    }
    String[] s = get2doublesSameExp(1.234e-6,11.234e-6);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 2011-10-09
      • 1970-01-01
      • 2010-09-26
      • 2012-02-09
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多