Double.toString()
I’ve been writing things in Java for a hell of a lot years now and few things come up in the base language that surprise me or mess me up - usually the only new things are external libraries and APIs. But today something caught me. There was a method I was responsible for that essentially converts database query results into XML. One of the fields was for money, and represented as a double (with varying amounts of decimal places due to it being the aggregate of other data). Normally using Double.toString() would give a normal number like “958725.48″. For some results though (larger ones) the string given by the toString() method was in scientific notation with an exponent, like “9.5872548E5″. So I checked the documentation for the method and sure enough the behaviour is documented:
If m is less than 10-3 or greater than or equal to 107, then it is represented in so-called “computerized scientific notation.”…
I can deal with things like this, but I just don’t get the rationale behind it - if you’re converting a double to a String representation, it’s not going to overflow since it returns a new String object. So in the end I had code like this:
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
columnValue = nf.format(double);
I guess I learned something new, but it was still kind of a waste of time and if I was personally responsible for that method’s behaviour I would have made the conversion to scientific notation an option and not a conditional.