当前位置: 动力学知识库 > 问答 > 编程问答 >

c# How do I format a double to a string and only show decimal digits when necessary?

问题描述:

I found this question in StackOverFlow but it didn't solve my problem.

How do I format a double to a string and only show decimal digits when necessary?

Weight

0.500

18.000

430.000

by the solution in above url my result show in this form:

Weight

0.5

18

430

and my problem is in decimal digits, I want show decimal digits in 3 digit,like this:

Weight

0.500

18

430

网友答案:

I think you can't do what you want with single string.Format(). So you can use a clause:

if(weight % 1.0 > 0){
     string.Format("{0:0.000}", weight)
}
else {
     string.Format("{0:0}", weight)
}

Or even better:

string.Format(weight % 1.0 > 0 ? "{0:0.000}" : "{0:0}", weight)  

EDIT: Sorry missed a bit =))

EDIT: If you need to floor result you can use:

string.Format(weight % 1.0 >= 0.001 ? "{0:0.000}" : "{0:0}", weight)  
网友答案:

You can use Digit placeholder # with Zero placeholder 0 after dot . in string format.

string num = d % 1 == 0 ? d.ToString(".###") : d.ToString(".000");

Digit placeholder

Replaces the pound sign with the corresponding digit if one is present; otherwise, no digit appears in the result string.

Zero placeholder

places the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

This msdn article Custom Numeric Format Strings explains how the number could be formated.

网友答案:

Try

 num.ToString("G3") // for 3 significant digits

http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

网友答案:

You can use like below method:

Usage:

    string format1 = GetFormat(123.4567);
    string format2 = GetFormat(123.45);
    string format3 = GetFormat(123.0);
    //format1 = 123.46
    //format2 = 123.45
    //format3 = 123

    private static string GetFormat(double d)
    {            
        string format;
        if (d == Convert.ToInt32(d))
            format = string.Format("{0:0.##}", d);
        else
            format = string.Format("{0:0.00}", d);

        return format;
    }

For more information:

http://csharpexamples.com/c-string-formatting-for-double/

http://msdn.microsoft.com/en-us/library/vstudio/0c899ak8%28v=vs.100%29.aspx

网友答案:

I found the solution:

string[] strList = Weight.ToString().Split('.');//or ',' for diffrent regions
if(strList[1] == "000")
     str = string.Format("{0:#,0.########}", b);

thank you:)

分享给朋友:
您可能感兴趣的文章:
随机阅读: