问题
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.
回答1:
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.
回答2:
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.
回答3:
If you know you always want two places after the decimal you can right-fill with zeros.
it is not the job of the double type to keep track of your desired display format.
回答4:
Double does not store redundant zeros. In your view or presentation layer, you might want to format it to show you want it to appear, e.g., String.Format("{0:#.##}", doubleVariable)
来源:https://stackoverflow.com/questions/4415596/preventing-double-parse-from-removing-trailing-zeros-after-decimal-place