简体   繁体   中英

Why convert value of Float to String and String to Float are not same in java

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.

  1. Computer floating point types are base-2
  2. It is a mathematical fact that the mapping between (finite precision) base-2 floating point and decimal notation (base 10) is not exact for all values. (Just like you can't write 1/3 exactly in decimal notation ... unless you have an infinite piece of paper.)

Observations:

  1. You can reduce rounding errors by using double rather than float .
  2. You can reduce rounding errors even further by using BigDecimal .
  3. You can hide rounding errors on output by displaying numbers with less precision, and rounding to the nearest ...
  4. In some cases you cannot eliminate rounding errors entirely.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM