Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Formatting output - 2 decimal places

Author  Topic 

Beady999
Starting Member

4 Posts

Posted - 2009-04-06 : 11:11:39
Hi,

I'm recovering data from an SQL table using C#.

I have an object that is DR["budget"] I can place this into a text box using:

budget.Text = DR["budget"].ToString();

but it displays as 5000.0000 even though the column in the table is declared as 'Money' (how many currencies use 4 dec places?)

How can I get it to display as just 5000.00 ?

I've tried a variety of suggestions from the web, but none seem to get anywhere close.


Regards,
Bernard D

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2009-04-06 : 11:58:10
C# gives you a lot of flexibility in formatting the data. For example:
budget.Text = Convert.ToDecimal(DR["budget"]).ToString("N2")
will format it with 2 decimal places.

If the data returned can have nulls, you should to compare against DBNull.Value and avoid the conversion if true. If the data may contain non-numeric results, you should use Decimal.TryParse rather than Convert. Binding the data to the text box and setting the format property of the text box may automatically take care of these special cases.

Numeric format strings with examples are described here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

If you want to format as currency with 2 decimal places and with a preceding $ sign, you would use C2 rather than N2.

It probably is illegal for us to discuss C# and format strings here :--) You will get better and more in-depth answers on a C# forum such as codeguru
Go to Top of Page

Beady999
Starting Member

4 Posts

Posted - 2009-04-06 : 12:31:33
Many thanks, I was missing the 'convert.' bit off the front.


Regards,
Bernard D
Go to Top of Page
   

- Advertisement -