将字符串转换为双精度型,小数点后2位小数点、字符串、转换为、精度

2023-09-04 02:17:24 作者:悟空好性感,豹纹加钢管

一切开始与code这些简单的几行:

All began with these simple lines of code:

string s = "16.9";
double d = Convert.ToDouble(s);
d*=100;

结果应该是1690.0,但事实并非如此。 d等于1689.9999999999998。 所有我想要做的是圆一个双重价值与小数点后2位。 这是我的职责。

The result should be 1690.0, but it's not. d is equal to 1689.9999999999998. All I want to do is to round a double to value with 2 digit after decimal separator. Here is my function.

private double RoundFloat(double Value)
{
    float sign = (Value < 0) ? -0.01f : 0.01f;

    if (Math.Abs(Value) < 0.00001) Value = 0;

    string SVal = Value.ToString();
    string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
    int i = SVal.IndexOf(DecimalSeparator);
    if (i > 0)
    {
        int SRnd;
        try
        {
            // вземи втората цифра след десетичния разделител
            SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1));
        }
        catch
        {
            SRnd = 0;
        }

        if (SVal.Length > i + 3)
            SVal = SVal.Substring(0, i + 3);
        //SVal += "00001";

        try
        {
            double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal);
            //result = Math.Round(result, 2);
            return result; 
        }
        catch
        {
            return 0;
        }
    }
    else
    {
        return Value;
    }

但同样同样的问题,从字符串转换为加倍不工作,因为我想要的。 一种解决方法这个问题是连接00001的字符串,然后使用Math.Round功能(评论在上面的例子)。

But again the same problem, converting from string to double is not working as I want. A workaround to this problem is to concatenate "00001" to the string and then use the Math.Round function (commented in the example above).

这双值乘以100(为整数)是发送到设备(收银),这值必须是正确的。

This double value multiplied to 100 (as integer) is send to a device (cash register) and this values must be correct.

我使用VS2005 + .NET CF 2.0

I am using VS2005 + .NET CF 2.0

有另一种更优雅的解决方案,我不满意这一点。

Is there another more "elegant" solution, I am not happy with this one.

推荐答案

双打不能完全重新present 16.9。我建议你​​将其转换为十进制来代替:

Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:

string s = "16.9";
decimal m = Decimal.Parse(s) * 100;

double d = (double)m;

您可能只是想继续使用十进制而不是,既然你说你会使用它的金融需求。请记住,十进制是为了准确地再适合在precision present十进制数,而只能完全重新的做present二进制数。

You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.