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.
"%10s" Format a string with the specified number of characters and also right justify. "%-10s" Format a string with the specified number of characters and also left justify.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With