java equivalent to printf(“%*.*f”)

为君一笑 提交于 2019-11-29 09:11:27

I use

int places = 7;
int decimals = 3;

String.format("%" + places + "." + decimals + "f", floatValue);

A little ugly (and string concatenation makes it not perform well), but it works.

System.out.print(String.format("%.1f",floatValue));

This prints the floatValue with 1 decimal of precision

You could format the format :

String f = String.format("%%%d.%df", 7, 3);
System.out.println(f);
System.out.format(f, 111.1111);

This will output :

%7.3f
111,111

You could also use a little helper like this :

public static String deepFormatter(String format, Object[]... args) {
    String result = format;
    for (int  i = 0; i != args.length; ++i) {
        result = String.format(result, args[i]);
    }

    return result;
}

The following call would then be equivalent as the code above and return 111,111.

deepFormatter("%%%d.%df", new Object[] {7, 3}, new Object[] {111.1111});

It's not as pretty as printf, and the input format can become cluttered, but you can do much more with it.

Its like this...

%AFWPdatatype

A - Number of Arguments

F - Flags

W - Width

P - Precision

String.format("%.1f",float_Val);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!