Money type

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 3 17:45:44 UTC 2020


On 1/3/20 12:14 PM, Ola Fosheim Grøstad wrote:
> And please forget the idea that fixed point is exact, it most certainly 
> is not! :-)

Exactness according to the terms of what is agreed upon for discrete 
units. Not according to some IEEE standard where the discreteness varies 
based on value.

If you want complete exactness, rational numbers are what you need, and 
I do use those in other places.

> 
> Let me give an example:
> 
> Assume that you have 21% VAT and prices are given including tax, then in 
> order to find the price without VAT you have to calculate price/1.21, 
> but in fixed point that becomes price*100/121 which will have a 
> remainder. So then you also have to deal with the remainder, so not 
> exact at all.
> 
> If you want the price without VAT, rounded you'll have to do:
> 
>     (price * 200 / 242 + 1) / 2
> 
> If you want to deal with the price without VAT with no rounding, you 
> will have to emulate rational numbers...
> 
> 

You are starting from an inexact figure to begin with (almost certainly 
it has been rounded). Of course your figures will not be exact, in any 
number system.

If tax is added on top of the total taxable cost, then a per-item cost 
is going to be inexact anyway (some will have one extra cent added due 
to the rounding).

Generally you are only dealing with transaction amounts in full cents, 
unless there is some electronic form of payment, and in that case, you 
have a limit as to what you are dealing with. I'll take inexactness 
based on rounding, but consistent and agreed upon rules, over 
inexactness of actual value, any day.

I'll give you an example, you go to the store and an item is on sale for 
3 for $5.00. The cost for the first item is $1.67, the cost for the 
second item is $1.67, the cost for the third is $1.66. Total is $5. But 
if you buy one item, it's $1.67. I can understand the rules without any 
issue. I can't tell you what happens when you multiply 5.0/3.0 * 3.0 (or 
even 500.0/3.0 * 3.0). Most likely it's fine, but I can't tell you that 
for sure it is going to be fine.

You can create systems that have rules for how to deal with imprecision, 
but you need to base it on types that are easy to predict and don't 
require IEEE experts to understand.

-Steve


More information about the Digitalmars-d mailing list