防止 double.Parse 删除小数点后的尾随零?
当使用 double.Parse 时,它似乎喜欢从我正在转换的字符串中去掉任何尾随(无关紧要的)零。我希望 double.Parse 保留到小数点后的位置。例如,下面是一些代码:
tobereturned.MouseSensitivty = double.Parse(String.Format("{0:#.##}", tempstring[1]));
Debug.WriteLine("Converted " + String.Format("{0:#.##}", tempstring[1]) + " to " + tobereturned.MouseSensitivty);
调试器然后写入
将 4.00 转换为 4
所以看起来 double.Parse 在这里做了一些可疑的事情。 PS MouseSensitivity也是double类型,所以我不能对其进行任何字符串操作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的问题毫无意义。双精度数从一开始就没有“小数点后的位数”。它们不会在内部存储任何看起来像“数字的十进制表示形式”的东西。事实上,它们不会在内部存储任何看起来像可识别文本的内容。
它报告 4,因为 4.00 正好等于 4。它根据将数字转换为文本的默认规则,将数字“正好四,没有小数部分”显示为文本。
请阅读此内容。是的,它很长,而且很困难,但是如果没有真正理解这些材料,就不可能正确使用浮点数字类型 - 而且它也没有无论您使用什么语言。
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.
double
数据类型只是一个数字;它不会跟踪被解析以创建值的字符串。它的字符串表示仅在调用.ToString()
时才起作用。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.如果您知道总是想要小数点后两位,则可以在右侧填充零。
跟踪您想要的显示格式不是 double 类型的工作。
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.
Double 不存储多余的零。在视图或表示层中,您可能需要对其进行格式化以显示您希望它出现,例如 String.Format("{0:#.##}", doubleVariable)
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)