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.
This question is related to
java
android
floating-point
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
Try looking at the BigDecimal Class. It is the go to class for currency and support accurate rounding.
You can make use of DecimalFormat
to give you the style you wish.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.
Source: Stackoverflow.com