Atom Feed SITE FEED   ADD TO GOOGLE READER

Champagne Floats

Suppose you've got a string that contains a floating point number: "3.5" or "2.5E-3". Your goal is to get a float from that number. There are a few different techniques to try...

If you're familiar with parseDouble(), you could use that and then cast:
    String s = ...;
float a = (float) Double.parseDouble(s);

Or you could save some bits and parse directly using parseFloat():
    String s = ...;
float b = Float.parseFloat(s);


Do the two mechanisms yield the same result?


Ponder the problem, and when you're ready you can read my analysis in the comments...
Neither floats nor doubles have infinite precision. For some number n1 exactly expressible as a float, there's a next float n2. Between the two exist real numbers that have no perfect representation as a float.

But many of these real numbers between n1 and n2 do have an exact representation as a double.

To create an analogy, suppose that floats can represent only whole numbers: 1.0, 2.0, 3.0. Similarly, doubles can represent both whole numbers and half numbers: 1.0, 1.5, 2.0, 2.5, 3.0.

Given the input string "1.4":
A: the nearest float is 1.0
B: the nearest double is 1.5
C: the float nearest to B is 2.0

And so we can intuit that the two mechanisms will not yield the same result for values like "1.4" that would get rounded twice. For doubles and floats, "2.1019476964872256E-45" is such a value.
Could you please remove the tons of trojans/viruses on publicobject.com. Chrome warns about it. I almost lost my laptop getting the "Antivirus System Pro" when downloading the glazed lists impl...