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.
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 %.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
In order to round float and double numbers in Java, we use the java. lang. Math. round() method.
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
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
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