Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 427
gcode Avatar asked Dec 11 '10 06:12

gcode


2 Answers

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.

like image 61
Karl Knechtel Avatar answered Oct 29 '22 07:10

Karl Knechtel


The double data type is simply a number; it doesn't keep track of the string that was parsed to create the value. Its string representation only comes into play when .ToString() is called.

like image 2
Phil Hunt Avatar answered Oct 29 '22 06:10

Phil Hunt