如何解决这个转换问题?

时间:2012-10-12 12:15:30

标签: c# .net user-interface dll numbers

我创建了一个GUI,它将一个值编号输入另一个程序并将它们存储在tags中。我有一个奇怪的转换问题。当我输入8.5时,我得到一个字符串8.500000000000000 ...所以我使用TryParseDouble.ToString()方法来解决这个问题。但奇怪的是,当我尝试使用6.9时,字符串变为6.9000000005367431600000.I使用2 dll可能是导致此问题的原因。我已经阅读了这个Decimals explanation,但我不明白这是如何解决我的问题的。如何解决这个转换问题?

我的转换方法

    private bool TryWrite()
            {
// Read() returns a string(which represents int,double, float or string) read from another application
                string Oldcopy = _inTouchWrapper.Read(tagNameBox.Text);
// Write() Write my input number into the application stored in a specific tag
                _inTouchWrapper.Write(tagNameBox.Text, ValueBox.Text);
//OldCopy is to input back the old copy is the Write (new copy) cannot be performed
                string newCopy = _inTouchWrapper.Read(tagNameBox.Text);

                if (ValueBox.Text == Double.Parse(newCopy).ToString())
                {
                    return true;
                }
                else
                {
                    _inTouchWrapper.Write(tagNameBox.Text, Oldcopy);
                    return false;
                }
            }

有关软件/和我的代码的更多说明。该软件有标签ex:Alarm1,TimeString ...... 每个标记都有一个类型(int,real(浮点数),字符串)和一个值。该值取决于类型。如果标签类型是int,我不能输入5.6。所以我创建了这个方法,验证输入值是否确实可以添加到软件中。 工作原理:我在软件中输入一个值,将其读回,如果添加的值与读取值匹配,我确实输入了它。另外,我输回了oldCopy。

1 个答案:

答案 0 :(得分:1)

字符串“6.9”似乎没有直接转换为double。如果首先转换为float,然后再转换为double。这是一个例子:

var f = float.Parse("6.9");
var d = (double)f;
System.Diagnostics.Debug.WriteLine(d.ToString()); //6.90000009536743

PS:为什么你没有与'8.5'相同的问题是它可以完全以二进制形式表示。