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

陌路散爱 提交于 2019-12-18 05:43:32

问题


In C, the printf() statement allows the precision lengths to be supplied in the parameter list.

printf("%*.*f", 7, 3, floatValue);

where the asterisks are replaced with first and second values, respectively.

I am looking for an equivalent in Android/Java; String.format() throws an exception.

EDIT: Thanks, @Tenner; it indeed works.


回答1:


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.




回答2:


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

This prints the floatValue with 1 decimal of precision




回答3:


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.




回答4:


Its like this...

%AFWPdatatype

A - Number of Arguments

F - Flags

W - Width

P - Precision

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



来源:https://stackoverflow.com/questions/12375768/java-equivalent-to-printf-f

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