I will be working for a company where they are programming for Financial Institutions and I will be working with money a lot. Before that it wasn't a major concern for me because I've been doing small money things and Double was enough at some point but now even 1 penny is darn important.
I think everyone may know the
Dim mValue as Decimal = 100 'seems the best type for now
mValue = mValue / 3
Console.WriteLine(mValue)
Console.ReadLine()
mValue = mValue * 3
Console.WriteLine(mValue)
'Outputs 99.9999999999999999999999999... and never hits 100
So how can I get over this problem and find even better precise results?
Thanks.
When dealing with money you should never divide like that. You should allocate an amount as evenly as possible, getting a list of allocations as a result, e.g.:
100 allocated by 3 = [ 33, 33, 34 ]
Someone must get that extra penny.
Also, it's simpler to use an integer that represents the number of pennies than to use a decimal number.
And, encapsulate money operations is a dedicated class. Take a look at the Money pattern.
If you need to be able to perform arbitrary division, it sounds like you'll need a representation of a rational number (a fraction). I don't believe .NET provides one by default, and you'll have, um, "fun" implementing it in a way which performs as well as the built-in numeric types. That may get you going for addition, subtraction, multiplication and division - but it won't help if you need irrational numbers too (e.g. taking square roots).
Are you sure you're going to be dividing by 3 though? Are you sure you can't round to (say) the nearest 1000th of a penny? You should find out what the exact requirements are around your calculations - I doubt that you really need to be infinitely precise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With