条件格式化输出

时间:2014-07-03 09:42:30

标签: java formatter

我只能访问这样的函数(意味着我无法更改此函数的输入或签名):

public void log( String fmt , final Object... args )
{
    fmt = fmt.replace( "%f" , "%1.3e" );
    System.out.print( String.format( Locale.US , fmt , args );
}

我想将fmt更改为包含%5.2f%1.3e(仅限示例),具体取决于它所代表的实际小数值(实现的类型)每个小数值的相同位数)。

让我们说6位+ 1点:

1234.56789 becomes 1234.56
123.456789 becomes 123.456
12.3456789 becomes 12.3456
...
0.00123456789  becomes 1.234e-3 
0.000123456789 becomes 1.234e-4
...

有人会怎么做?

1 个答案:

答案 0 :(得分:3)

通过"相同数字的数字",我假设您的意思是"相同数量的字符",这是记录功能的常见要求。

对于6位+ 1个点,以下代码将为每个数字输出7个字符:

import java.util.Locale;

public class TestLog {
    public static void main(String[] args) {
        log("%f", 1234.56789);
        log("%f", 123.456789);
        log("%f", 1.3456789);
        log("%f", 0.0012345678);
        log("%f", 0.0001);

    }

    public static void log(String fmt, final Object... args) {
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof Number) {
                double d = (Double) args[i];
                if (d < 0.01) 
                    // Too small for precision 2, switch to scientific notation
                    fmt = fmt.replace("%f", "%07.1e");
                else
                    fmt = fmt.replace("%f", "%07.2f");
            }
        }

        System.out.println(String.format(Locale.US, fmt, args));
    }
}

输出正在:

1234.57
0123.46
0001.35
1.2e-03
1.0e-04

在任何情况下,占位符中的07部分都是最重要的,因为它保证了输出的最小宽度。前导0标志确保输出用零填充,但如果您想要空格,则可以将其取出。