user1982231
user1982231

Reputation: 25

How to format string with floating point?

In database I have a PRICE field type of float with value 54342.76 and I want to display it on gridview as 54,342.76. How can format this values?

Upvotes: 1

Views: 1341

Answers (4)

Jeremy Thompson
Jeremy Thompson

Reputation: 65732

In the past I have used this: http://www.codeproject.com/Articles/11531/Money-DataType

It formats money perfectly when used in a DataGridView column.

Upvotes: 0

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23695

String.Format("{0:n}", 54342.76F)

The N method is a good solution since it should respect the user's locale while others like:

String.Format("{0:#,###,###.##}", 54342.76F)

Could bypass current culture in some situations. Use {0:n0} instead of {0:n} if you want to display the number without decimals.

Upvotes: 1

Z .
Z .

Reputation: 12837

this is what I use:

x.ToString("c")

Upvotes: 1

horgh
horgh

Reputation: 18563

Try

float f = 54342.76F;
string s = f.ToString("0,0.000", CultureInfo.InvariantCulture);
Console.WriteLine(s);

You could use c specifier instead, however it prints currency sign also. Use CultureInfo.InvariantCulture as in some localizations , thousands separator may be missing.

Also read Decimal.ToString Method, Standard Numeric Format Strings, Custom Numeric Format Strings

Upvotes: 3

Related Questions