Tony
Tony

Reputation: 1155

formatting floats to different precisions

I have to format a float in Java differently depending on different values. For instance

23 format to 23
24.15 format to 24.15
30.249 format to 30.25
42.7 format to 42.7

That is, round up from the 100th place but do not display final 0's to the right (that is 3.4 instead of 3.40 and 7 instead of 7.0) etc. But again two decimal places max.

I was playing around with String.format but cannot figure out the correct format. I do need to format the float and write it to a String though.

Anyone have an idea what the format should be, or some other way to format the number (into a string)?

Upvotes: 1

Views: 74

Answers (2)

Austin
Austin

Reputation: 756

To start you going to want to add .005 to your float so it rounds properly.

floatvariable = floatvariable+.005;

Then you need to multiply it by a hundred.

floatvariable = floavariable*100;

Now you need to cast it to an integer this will remove any extra numbers.

int intvariable = (int)floatvariable;

Finally, you can divide that number by a hundred and put it back in the float variable.

floatvariable = (float)intvariable/100

Now you should have a number rounded to the nearest thousandth.

Upvotes: -1

Andreas
Andreas

Reputation: 159086

Use new DecimalFormat("0.##"):

# - Digit, zero shows as absent

Test

NumberFormat fmt = new DecimalFormat("0.##");
System.out.println(fmt.format(23f));
System.out.println(fmt.format(24.15f));
System.out.println(fmt.format(30.249f));
System.out.println(fmt.format(42.7f));
System.out.println(fmt.format(53.006f));

Output

23
24.15
30.25
42.7
53.01

Upvotes: 3

Related Questions