如何显示双精度而不截断字符串格式的浮点数?

时间:2019-03-19 21:34:00

标签: java formatting string-formatting

我正在上普林斯顿大学的算法课程,并且第一个编程任务需要以这种方式输出结果:

mean                    = 0.5929934999999997
stddev                  = 0.00876990421552567
95% confidence interval = [0.5912745987737567, 0.5947124012262428]

我考虑过字符串格式化,因为在他们的头脑中没有人会计算缩进的空格:

    String confidence = "95% confidence interval";
    int width = confidence.length();
    String f = "%-".concat(String.valueOf(width)).concat("s = ");
    System.out.printf(f.concat("%f\n"), "mean", stats.mean());
    System.out.printf(f.concat("%f\n"), "stddev", stats.stddev());
    System.out.printf(f.concat("[%f, %f]"), confidence, stats.confidenceLo(), stats.confidenceHi());

但令我遗憾的是,程序将截断两次截断以使其浮动:

mean                    = 0.591316
stddev                  = 0.009776
95% confidence interval = [0.589400, 0.593232]

这么说,有没有办法格式化整个双精度数字?

3 个答案:

答案 0 :(得分:4)

在这种情况下使用DecimalFormat,例如:

    double mean = 0.592993499999999;
    NumberFormat formatter = new DecimalFormat("#0.000000000000000");
    System.out.println(formatter.format(mean));

答案 1 :(得分:0)

使用16个小数位格式“%.16f”

String confidence = "95% confidence interval";
int width = confidence.length();
String f = "%-".concat(String.valueOf(width)).concat("s = ");
System.out.printf(f.concat("%.16f\n"), "mean", stats.mean());
System.out.printf(f.concat("%.16f\n"), "stddev", stats.stddev());
System.out.printf(f.concat("[%.16f, %.16f]"), confidence, stats.confidenceLo(), stats.confidenceHi());

答案 2 :(得分:0)

我使用了String.valueOf(aDoubleNumber)方法并将printf语句中的%f更改为%s。这对我有用。

public static void main(String[] args)
    {
        double mean = 0.5929934999999997;
        double stddev = 0.00876990421552567;
        double confidenceLo = 0.12345666612123;
        double confidenceHi = 0.123456784435369;

        String confidence = "95% confidence interval";
        int width = confidence.length();
        String f = "%-".concat(String.valueOf(width))
            .concat("s = ");

        // changed the %f to %s and used String.valueOf method to convert first
        System.out.printf(f.concat("%s\n"), "mean", String.valueOf(mean));
        System.out.printf(f.concat("%s\n"), "stddev", String.valueOf(stddev));
        System.out.printf(f.concat("[%s, %s]"), confidence,
                (String.valueOf(confidenceLo)), String.valueOf(confidenceHi));
    }

输出:

  

平均值= 0.5929934999999997

     

stddev = 0.00876990421552567

     

95%置信区间= [0.12345666612123,0.123456784435369]