Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to round a float to two decimal places in Java [duplicate]

Possible Duplicate:
How to round a number to n decimal places in Java

I am having difficulties rounding a float to two decimal places. I have tried a few methods I have seen on here including simply just using Math.round(), but no matter what I do I keep getting unusual numbers.

I have a list of floats that I am processing, the first in the list is displayed as 1.2975118E7. What is the E7?

When I use Math.round(f) (f is the float), I get the exact same number.

I know I am doing something wrong, I just am not sure what.

I just want the numbers to be in the format x.xx. The first number should be 1.30, etc.

like image 229
lonewookie Avatar asked Jun 17 '12 15:06

lonewookie


People also ask

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you convert double to 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you round a float in Java?

In order to round float and double numbers in Java, we use the java. lang. Math. round() method.


2 Answers

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118 

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118); // 1.30 
like image 167
Alexander Avatar answered Sep 27 '22 16:09

Alexander


If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d; NumberFormat formatter = NumberFormat.getCurrencyInstance(); String output = formatter.format(d); 

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String output = formatter.format(d); 

Which will output 2.30

like image 37
Kevin Coppock Avatar answered Sep 27 '22 16:09

Kevin Coppock