Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java equivalent to printf("%*.*f")

Tags:

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.

like image 768
vedavis Avatar asked Sep 11 '12 18:09

vedavis


People also ask

What does %- 10s mean in Java?

"%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.

What is %s and %D in Java?

%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"

What is %d for in Java?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character.


2 Answers

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.

like image 93
James Cronen Avatar answered Sep 17 '22 13:09

James Cronen


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

This prints the floatValue with 1 decimal of precision

like image 32
brthornbury Avatar answered Sep 19 '22 13:09

brthornbury