I had a go at producing a J submission for the RosettaCode Currency
task<http://rosettacode.org/wiki/Currency>. It does the job, but I
figure that doing exact calculations with currency
is something that some forum members do routinely and wanted to get some
ideas of better ways to approach it.

This is the Task description:

"""

Show how you might represent currency in a simple example, using a data
type that represent exact values of dollars and cents. Note for example
that 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, 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 the total price before tax, the tax, and the
total with tax, and show results on this page. 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, and 23683000000000006.16. Dollar
signs and thousands separators are optional.

"""

Below is my J solution - how to deal with "decimal type" routinely?:

require 'format/printf'
toCents=: _99 ". }:&.(_2&|.) {.~ 3 + '.' i.~ ]
fromCents=: [: ,&'.'&.(_2&|.) ":
hamburger_price=: toCents '5.50'
milkshake_price=: toCents '2.86'
tax_rate=: 0.0765

total_before_tax=: +/ 4000000000000000 2 *&x: hamburger_price , milkshake_price
tax=: tax_rate ([: <. 1r2&+)@*&x: total_before_tax
total=: total_before_tax + tax

(fromCents&.> total_before_tax,tax,total) printf~ noun define
    Total before tax: %22s
                 Tax: %22s
               Total: %22s
)
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to