问题与格式化双变量在C#中的文本框显示 [英] Issue with Formatting a double variable to show in textbox in C#

查看:99
本文介绍了问题与格式化双变量在C#中的文本框显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道为什么这个Format命令产生以下奇怪的结果:

Does anyone know why this Format command produces the following strange results:

textbox1.Text = String.Format("{0:+;-}{0,7:0.000;0.000}", dblVariable);

下面是奇怪的结果(检查格式化文本的符号 - 符号是不正确的人数较少小于0.5):

Here are the strange results (check the signs of the formatted text - the sign is incorrect for numbers smaller than 0.5):

dblVariable       textbox1.Text
-0.100000         + 0.100
-0.200000         + 0.200
-0.300000         + 0.300
-0.400000         + 0.400
-0.500000         - 0.500

感谢

推荐答案

在MSDN 本文介绍的问题。看看什么是下称到两段

The article in MSDN describes the issue. Look at what is said next to Two sections:

如果数量要格式化是否定的,但
舍入后变成零,根据在所述第二部分中的格式,将所得
零被格式化根据第一部分

If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, the resulting zero is formatted according to the first section.

在您的情况中,符号的格式为: {0:+, - } 。这实际上意味着,没有任何数字格式,只需登录格式。所以四舍五入到这种格式时,它必须被舍入到整数。因此,在 -0.1 的情况下 -0.4 数四舍五入为0,它使用第一部分(+),但 -0.5 四舍五入到 1 ,所以第二部分( - )。使用

In your case the format of the sign is {0:+;-}. This effectively means that there is no number format, just sign format. So when rounding to this format it must be rounded to a integer number. So in case of -0.1 to -0.4 the number is rounded to 0, which uses first section (+), but -0.5 is rounded to -1, so second section (-) is used.

您可以只用单一的格式修正:

You can fix it by only using single format:

textbox1.Text = String.Format("{0,7:+ 0.000;- 0.000}", dblVariable)

这篇关于问题与格式化双变量在C#中的文本框显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆