Variable type Money/Currency

  • Thread starter Thread starter tshad
  • Start date Start date
T

tshad

What is the best way to handle money in C#?

Do you use float type?

Then how do you handle rounding problems with cents as well as how best to
display it?

Thanks,

Tom
 
tshad,

For money, I would use the Decimal type (decimal is the alias in C#).
It is guaranteed to be precise (up to a certain number of places, enough for
financial calcs, IMO). However, the downfall is that using it is slower, so
you have to pick your poison.

Hope this helps.
 
Hi,

The bigger precision is by using Decimal.
To display it friendly you could use Decimal.ToString( "C" );

cheers,
 
Tshad,

The best you can do with money is sent it to me, I can use a lot.

However be aware that in the version 2005 the rounding has more
possibilities. Because at the moment is all going by bankings rounding,
which is in my opinion rarely used.

For the rest see Chris his message.

Cor
 
Chris Dunaway said:
You'd probably be better off using a Decimal type

But how do you add cents?

I tried doing:

deductionTotals += 100.15

and got 2 errors:

Literal of type double cannot be implicitly converted to type 'decimal';
use an 'M' suffix to create a literal of this type

and

Operator '+=' cannot be applied to operands of type 'decimal' and
'double'

Do I need to take all my calculations and multiply them by 100?

Thanks,

Tom
 
The help for CS0664 is pretty clear. By default, doubles cannot be
implicitly converted to decimal. 100.15 is considered a double. To
make it decimal write 100.15M:

deductionTotals += 100.15M;

http://www.peterRitchie.com/
 
The help for CS0664 is pretty clear. By default, doubles cannot be
implicitly converted to decimal. 100.15 is considered a double. To
make it decimal write 100.15M:

deductionTotals += 100.15M;

I got it now.

That answered the question of the error message I was getting. All literals
need to have an M after it when dealing with decimals

If you wanted to add a "double" type variable to a decimal, since it can't
be done implicitly, would you have to use some sort of "Convert" function
first?

Thanks,

Tom
 
Use:

deductionTotals += 100.15m;

M is a "literal suffix" that tells the compiler to treat your literal as a
Decimal.
 
PW said:
Use:

deductionTotals += 100.15m;

M is a "literal suffix" that tells the compiler to treat your literal as a
Decimal.

It's interesting that they didn't use "D" instead of "M" :)

Thanks,

Tom
 
Back
Top