Is there a way in .NET to create a type derived from decimal that would be used as a currency, so it rounds the arithmetic operations to the desired number of decimal points.
If not, what are the best practice for it in .NET?
EDIT (motivation):
Let’s say I have a price:
125.00 Rep$
and I sell 0.25 pieces of it, that amounts to 31.25
Now, I have a discount of 15%, and to calculate discount and present it in absolute value I’ll have:
31.25 * .85 = 26.5625
If I use other way:
31.25 * .15 = 4.6875
If I let some 3rd party control to truncate it and display it, for example, I could have:
26.56 +
4.68 =
-----
31.24
And every accountant will eat your hearth if you give her something like that.
Add tax here, and problem multiplies further.
So, NO storing as much decimals and rounding it as late as possible. Create a class that will do it financially correct and store it as soon as possible rounded/truncated.
You certainly can’t create a type derived from
decimal, as it’s a struct – and you can’t create subtypes of structs.You could create your own
Currencystruct which contained a decimal, though. You’d want to overload all the arithmetic operators to basically perform the arithmetic on the contained decimal values and then round appropriately.For example:
(Obviously there’s a lot more needed here – in particular you’ll want to override
GetHashCodeandEquals, implementIEquatable<T>etc.)Is this definitely what you want though? I thought it was more common to keep as much precision as you could during intermediate operations, and only round at the last moment, e.g. for storage in a database or display to a user.