I have have taken 10 digit float value and tried to convert it to string to print in a readable format. Here is the program to check
public static void main(String[] args) {
String s1 = "2139095039";
String s2 = "2.13909504E9";
Float f1 = Float.valueOf(s1);
Float f2 = Float.valueOf(s2);
System.out.println("Are f1 and f2 are same:::" + (f1.equals(f2)));// TRUE
System.out.println("Are s1 and s2 are same:::" + (s1.equals(s2)));// FALSE
System.out.println("Are f1 and f2 string format type same:::"
+ (String.format("%.0f", f1)).equals(String.format("%.0f", f2)));// TRUE
System.out.println("S1 Float to String convertion:: " + String.format("%.0f", f1));// 2139095040
System.out.println("S2 Float to String convertion:: " + String.format("%.0f", f2));// 2139095040
}
My question here is when S1 and S2 values are same why after conversion to string type its printig 2139095040 instead of 2139095039?
In other words how can i print human readable format of scientific notation of 2.13909504E9?
For roughly the same reason that
0.333333333333333333333 * 3
is not 1.0. Rounding error.More specifically.
Observations:
double
rather thanfloat
.BigDecimal
.Note that there is a field of mathematics devoted to the mathematics of numerical computation: Numerical Analysis. If you really want to understand this stuff, how to deal with the effects of errors on computation, that's the field to study.