user
Task

Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.

Note

The **IEEE 754** binary floating point representations of numbers like   **2.86**   and   **.0765**   are not exact.

For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.

Use the values:

:   :   * 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers)
        * 2 milkshakes at $2.86 each, and
        * a tax rate of 7.65%.

(That number of hamburgers is a 4 with 15 zeros after it.   The number is contrived to exclude naïve task solutions using 64 bit floating point types.)

Compute and output (show results on this page):

:   :   * the total price before tax
        * the tax
        * the total with tax

The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.

The output must show dollars and cents with a decimal point.

The three results displayed should be:

:   :   * 22000000000000005.72
        * 1683000000000000.44
        * 23683000000000006.16

Dollar signs and thousands separators are optional.
assistant
(formerly Perl 6)

**Works with**: Rakudo version 2016.01

No need for a special type in Raku, since the Rat type is used for normal fractions.
(In order to achieve imprecision, you have to explicitly use scientific notation,
or use the Num type, or calculate a result that requires a denominator in excess of 2 \*\* 64. (There's no limit on the numerator.))

```
my @check = q:to/END/.lines.map: { [.split(/\s+/)] };
    Hamburger   5.50    4000000000000000
    Milkshake   2.86    2
    END

my $tax-rate = 0.0765;

my $fmt = "%-10s %8s %18s %22s\n";

printf $fmt, <Item Price Quantity Extension>;

my $subtotal = [+] @check.map: -> [$item,$price,$quant] {
    my $extension = $price * $quant;
    printf $fmt, $item, $price, $quant, fix2($extension);
    $extension;
}

printf $fmt, '', '', '', '-----------------';
printf $fmt, '', '', 'Subtotal ', $subtotal;

my $tax = ($subtotal * $tax-rate).round(0.01);
printf $fmt, '', '', 'Tax ', $tax;

my $total = $subtotal + $tax;
printf $fmt, '', '', 'Total ', $total;

# make up for lack of a Rat fixed-point printf format
sub fix2($x) { ($x + 0.001).subst(/ <?after \.\d\d> .* $ /, '') }

```

Output:

```
Item          Price           Quantity              Extension
Hamburger      5.50   4000000000000000   22000000000000000.00
Milkshake      2.86                  2                   5.72
                                            -----------------
                             Subtotal    22000000000000005.72
                                  Tax     1683000000000000.44
                                Total    23683000000000006.16
```