java equivalent to printf("%*.*f")
Asked Answered
N

4

20

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.

Nephron answered 11/9, 2012 at 18:31 Comment(0)
H
16

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.

Harbinger answered 11/9, 2012 at 18:33 Comment(0)
W
3
System.out.print(String.format("%.1f",floatValue));

This prints the floatValue with 1 decimal of precision

Wont answered 11/9, 2012 at 18:33 Comment(1)
@BelusC There are both. See docs.oracle.com/javase/1.5.0/docs/api/java/io/…Protium
A
2

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.

Arleyne answered 20/5, 2013 at 23:54 Comment(0)
B
0

Its like this...

%AFWPdatatype

A - Number of Arguments

F - Flags

W - Width

P - Precision

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

Body answered 11/9, 2012 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.