Quilnux

Hello,

I am pulling a "money" field from an SQL Database. When I add it to a listbox I use "GetDecimal()". The listbox results in data with 4 decimal places. I need to change this to 2 decimal places. How can I do this

Quilnux



Re: Visual C# General Decimal with 2 decimal places instead of 4

TilakGopi

Hi,

Convert it to string and get the substring what ever u want and convert the result back to decimal.

If u can give me the decimal (source value) and target decimal value, i'll also try.

Thanx,

Ch.T.Gopi Kumar.






Re: Visual C# General Decimal with 2 decimal places instead of 4

ThE_lOtUs

There's the: System.Math.Round






Re: Visual C# General Decimal with 2 decimal places instead of 4

Kane-

double d = 17.4501;
d = Math.Round(d, 2);

Edit: er.. Lotus seemed to beat me to it :)




Re: Visual C# General Decimal with 2 decimal places instead of 4

TilakGopi

Hi Kane,

it's decimal not double.

Thanx,

Ch.T.Gopi Kumar.






Re: Visual C# General Decimal with 2 decimal places instead of 4

Kane-

TilakGopi wrote:

Hi Kane,

it's decimal not double.




The library call is still the same :)

Decimal d = 17.3501m;
d = Math.Round(d, 2);




Re: Visual C# General Decimal with 2 decimal places instead of 4

TilakGopi

Oh,

That's great buddy.Getting new things,really.Thank you.

Regards,

Ch.T.Gopi Kumar.






Re: Visual C# General Decimal with 2 decimal places instead of 4

OmegaMan

Remember for monetary calculations you always want to use decimal. Double is accurate to only 15 positions. Check out this post Double Subtraction extra value unexpected. Also, you may not have this problem, but foreign databases sometimes truncate instead of round financial calculations and you will begin to find your values off so slightly.





Re: Visual C# General Decimal with 2 decimal places instead of 4

boban.s

You can use NumberFormatInfo and set the number of decimal places:
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.NumberDecimalDigits = 2;

so when you need to printout decimal number with two digits use this method:

decimalVariable.ToString("N", nfo);