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?

``Weight0.50018.000430.000``

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

``Weight0.518430``

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

``Weight0.50018430``

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;
}
``````

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

Top