将double转换为字符串并仅在需要时显示十进制值

时间:2014-05-21 17:43:18

标签: c# typeconverter

我想将以下3个双精度值转换为字符串。

Double value            converted string value
1                       1
1.200                   1.200
1.666                   1.666

我希望输出字符串值的格式与double相同。上述值1中的均值不具有任何十进制值,因此它将保持相同。在1.200的情况下,它将给我字符串1.200和1.666相同。但是我尝试了.ToString()方法,但它截断了1.200值的ZERO值。但我不想要这个。我想要字符串格式的实际值。

2 个答案:

答案 0 :(得分:1)

我承认我不喜欢这样做的想法,但是我为Double类型编写了一个扩展方法来格式化它。随意改变有趣的名字。 :)

public static class StupidDouble
{
    public static string StupidFormat(this double theValue)
    {
        // geth the double value to three decimal points
        string s = string.Format("{0:0.000}", theValue);

        // get the whole number value
        int check = (int) Math.Truncate(theValue);

        // if the format of the int matches the double, display without decimal places
        if (string.Format("{0:0.000}", check) == s)
        {
            s = check.ToString();
        }

        return s;
    }
}

答案 1 :(得分:1)

C#或任何其他语言(包括SQL)不会根据代码在代码中的表示形式对浮点类型(floatdouble)的值产生差异。

这意味着编译器在以下方面没有区别:

double v1 = 1;

double v2 = 1.000;

您所说的数据库(在评论中)也没有从中获取这些值。

数据库以某种方式显示小数的原因是由于应用于结果集的预定义格式。这可以由您使用的数据库工具定义,也可以取决于您的区域设置系统设置。无论如何,.NET框架为您提供了explicitly format your data的功能。

您需要确定哪种格式最适合您的需要使用它。例如,这将在点之后用4位小数格式化数字:

String.Format("{0:0.0000}", v1); // outputs 1.0000
String.Format("{0:0.0000}", v2); // outputs 1.0000 too

如果您已经知道所需的格式,请调整格式化字符串(第一个看起来像"{0:0000}"的参数最符合您的要求。