Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top