c# - toString保留小数位

标签 c# winforms textbox rounding tostring

有没有办法让“double.toString()”的结果字符串包含 double 的精确值?

例如

double d = 123.0   ->   toString() will be "123"

我找到了一些使用自定义格式 .toString("#.0") 的解决方案,但如果我想添加更多小数位,我会回到哪里我开始了

double d = 123.00   ->  toString("#.0") will be 123.0
double d = 123.0    -> toString("#.00") will be 123.00

我尝试这样做的原因是因为我有自定义文本框,这些文本框必须使用与实际显示的值不同的值,并且当尝试将您自己的值输入此文本框时,文本框会忽略您的当您尝试在小数位输入零时出现文本。因此,我需要 toString 值等于 double 的精确值,以便可以正确输入该数字。

谢谢

最佳答案

Is there a way to make the resulting string from a 'double.toString()' contain the exact value of the double?

确实包含 double 的确切值 - 但 double 不存储 123、123.0 和 123.00 之间的任何差异.

然而,

decimal 存储差值 - 如果您关心精确的小数位,则它更合适。

另一方面,听起来实际上您在错误的地方进行比较:

The reason I'm trying to do this is because I've got custom text boxes that must use a different value to the one thats actually displayed and when trying to enter your own value into this text box the textbox is ignoring your text when you try to enter zero in decimal places.

不要比较 string 值 - 解析值(decimaldouble),然后比较解析后的值。

这也将防止出现前导零的问题,其中“0123”和“123”表示相同的值,但它们是不同的字符串。

关于c# - toString保留小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14768709/

相关文章:

asp.net - OnTextChanged 事件未触发

silverlight-4.0 - Silverlight 4 TextBox 中的字符大小写

javascript - 文本在 Google 网上论坛中设置,帖子正文但不显示?

c# - 序列化 Protobuf 对象并使用 ØMQ/ZMQ 发送

c# - Graphics.DrawIcon 忽略比例变换?

c# - 与用于键入密码的文本框相关的问题

.net - 使用 Firebase/Pusher/Pubnub 在 .Net 桌面应用程序和 Web 应用程序之间来回推送通知

c# - Controller 的非异步方法是否会阻止其他用户在使用或锁定时进入?

c# - 在 C# 中传递变量

c# - .Net 形式焦点