Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get over losing pennies all the time?

Tags:

.net

currency

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.

like image 716
Tarik Avatar asked Aug 02 '11 16:08

Tarik


2 Answers

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.

like image 31
Jordão Avatar answered Nov 15 '22 07:11

Jordão


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.

like image 118
Jon Skeet Avatar answered Nov 15 '22 08:11

Jon Skeet