sanderson
sanderson

Reputation: 31

How to format a double with minimum precision

I have what I think is a simple problem. I have a collection of doubles that I want to display in a listbox. At a minimum, it should display three decimal places, however, if there are more than three digits, it should display them all.

I thought this would work, but it ends up just displaying the three decimal places:

    string.Format("{0} {1} {2}", freq.ToString("#0.000#", CultureInfo.CurrentCulture), hz, band);

Perhaps I am missing something. I don't really want to have to manually check the number of digits and transform the format block if necessary.

Thanks.

Upvotes: 1

Views: 1081

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Just add more "#" into your format string:

freq.ToString("#0.000#############", CultureInfo.CurrentCulture)

double has 15-16 digits precision, so 13 # should make it work for all cases.

Upvotes: 1

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14328

Probably:

freq.ToString("0.000#")

That will give you at least 3 digits after the decimal separator.

So:

4.25   --> 4.250

4.2555 --> 4.2555

Upvotes: 0

Related Questions