BaHaR
BaHaR

Reputation: 109

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

Upvotes: 3

Views: 3952

Answers (5)

BaHaR
BaHaR

Reputation: 109

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:)

Upvotes: 0

Adil
Adil

Reputation: 148110

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.

Upvotes: 4

Artyom Kharlamov
Artyom Kharlamov

Reputation: 213

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)  

Upvotes: 2

mrjoltcola
mrjoltcola

Reputation: 20842

Try

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

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

Upvotes: 1

turgay
turgay

Reputation: 458

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

Upvotes: 0

Related Questions