Pages

Friday, November 17, 2006

Converting Float to Double in a not so common way!!!!

I was working on a project and i had this strange but common problem. I was getting a value from an external system which was a primitive float. But, in our system it was all double. I had to convert the float to double without losing any precision. I tried to cast it directly into double but it didn't work. As, say, for example, if i was trying to convert 39.355F to double, then it turned out to be 39.35497... It always used to change the precision and in my case i didn't want it to change due to some processing i would be doing on it later. You could say i could have just rounded it off, but, in my case it wouldn't work. So, here i found a nice cute way to convert float to double as it is with out change in even a single digit also. It may seem it is not needed but believe me some times this all you can do. At least, this is what i could figure out when deadline was on my head.


public static double floatToDouble (float converThisNumberToFloat) {

String floatNumberInString = String.valueOf(converThisNumberToFloat);
double floatNumberInDouble = Double.parseDouble(floatNumberInString);
return floatNumberInDouble;

}

3 comments:

  1. I can say is a useful method!

    ReplyDelete
  2. Anonymous6:48 AM

    Unfortunately, this is very inefficient way.

    ReplyDelete
  3. I agree its in-efficient :) If there is any other way known, please post it. It will be very useful info.

    ReplyDelete