I am having trouble with large numbers in java while trying to store them in float variable.
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class testConversion {
public static void main(String[] args) {
String s = "135598877.50";
Float f = Float.parseFloat(s);
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(f);
System.out.println(df.format(f));
}
}
OUTPUT:
1.3559888E8
135598880.00
The output of this program is 135598880.00 and not 135598877.50.
Why this thing is happening and what is the best way of handling this? I don’t want truncation/rounding at all.
Regards,
Kaddy
floats are stored using IEE 754. They cannot store large numbers precisely.As you hinted in the question, you need to use
BigDecimal.