Preventing double.Parse from removing trailing zeros after decimal place?

TGP1994 picture TGP1994 · Dec 11, 2010 · Viewed 8.2k times · Source

When using double.Parse, it seems to like to string away any trailing (insignificant) zeros from the string that I'm converting. I would like double.Parse to keep to places after the decimal. For example, here is some code:

tobereturned.MouseSensitivty = double.Parse(String.Format("{0:#.##}", tempstring[1]));
Debug.WriteLine("Converted " + String.Format("{0:#.##}", tempstring[1]) + " to " + tobereturned.MouseSensitivty);

The Debugger then writes

Converted 4.00 to 4

So it seems like double.Parse is doing something fishy here. P.S. MouseSensitivity is also of the type double, so I can't do any string operations on it.

Answer

Karl Knechtel picture Karl Knechtel · Dec 11, 2010

Your question is meaningless. Doubles don't have "places after the decimal" in the first place. They don't store anything that looks remotely like a "decimal representation of a number" internally. In fact, they don't store anything internally that even looks like recognizable text.

It reports 4 because 4.00 is exactly equal to 4. It is displaying the number "exactly four with no fractional part" as text according to its default rules for converting numbers to text.

Please read this. Yes, it is long, and difficult, but it is simply not possible to use floating-point numeric types properly without a real understanding of this material - and it doesn't matter what language you're using, either.