Currency: Difference between revisions
m (→without commas: added a programming note about specifying the tax rate. -- ~~~~) |
m (→with commas: documented what a PERIOD LENGTH is (for the COMMA subroutine). -- ~~~~) |
||
Line 203: | Line 203: | ||
===with commas=== |
===with commas=== |
||
Programming note: the '''comma''' REXX subroutine (below) is a heavy-duty version that can handle any kind of number (numbers may have leading signs, imbedded blanks (after the sign), and it also handles numbers with leading and/or trailing currency symbols, and also exponentiated numbers (of any type or style of exponent notation). It also can support any character (or characters) for the separator, as well as a specified ''period length'' (the default is 3) |
Programming note: the '''comma''' REXX subroutine (below) is a heavy-duty version that can handle any kind of number (numbers may have leading signs, imbedded blanks (after the sign), and it also handles numbers with leading and/or trailing currency symbols, and also exponentiated numbers (of any type or style of exponent notation). It also can support any character (or characters) for the separator, as well as a specified ''period length'' (the default is '''3''' which indicates ''thousands'' separators). It can also limit the number of separators (normally a comma) to be inserted. |
||
<lang rexx>/*REXX pgm shows a method of computing the total price & tax for itemss */ |
<lang rexx>/*REXX pgm shows a method of computing the total price & tax for itemss */ |
||
numeric digits 200 /*let's get ka-razy.*/ |
numeric digits 200 /*let's get ka-razy.*/ |
Revision as of 00:18, 5 January 2014
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's 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.
Go
<lang go>package main
import (
"fmt" "log" "math/big"
)
// DC for dollars and cents. Value is an integer number of cents. type DC int64
func (dc DC) String() string {
d := dc / 100 if dc < 0 { dc = -dc } return fmt.Sprintf("%d.%02d", d, dc%100)
}
// Extend returns extended price of a unit price. func (dc DC) Extend(n int) DC {
return dc * DC(n)
}
var one = big.NewInt(1) var hundred = big.NewRat(100, 1)
// ParseDC parses dollars and cents as a string into a DC. func ParseDC(s string) (DC, bool) {
r, ok := new(big.Rat).SetString(s) if !ok { return 0, false } r.Mul(r, hundred) if r.Denom().Cmp(one) != 0 { return 0, false } return DC(r.Num().Int64()), true
}
// TR for tax rate. Value is an an exact rational. type TR struct {
*big.Rat
} func NewTR() TR {
return TR{new(big.Rat)}
}
// SetString overrides Rat.SetString to return the TR type. func (tr TR) SetString(s string) (TR, bool) {
if _, ok := tr.Rat.SetString(s); !ok { return TR{}, false } return tr, true
}
var half = big.NewRat(1, 2)
// Tax computes a tax amount, rounding to the nearest cent. func (tr TR) Tax(dc DC) DC {
r := big.NewRat(int64(dc), 1) r.Add(r.Mul(r, tr.Rat), half) return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())
}
func main() {
hamburgerPrice, ok := ParseDC("5.50") if !ok { log.Fatal("Invalid hamburger price") } milkshakePrice, ok := ParseDC("2.86") if !ok { log.Fatal("Invalid milkshake price") } taxRate, ok := NewTR().SetString("0.0765") if !ok { log.Fatal("Invalid tax rate") }
totalBeforeTax := hamburgerPrice.Extend(4000000000000000) + milkshakePrice.Extend(2) tax := taxRate.Tax(totalBeforeTax) total := totalBeforeTax + tax
fmt.Printf("Total before tax: %22s\n", totalBeforeTax) fmt.Printf(" Tax: %22s\n", tax) fmt.Printf(" Total: %22s\n", total)
}</lang>
- Output:
Total before tax: 22000000000000005.72 Tax: 1683000000000000.44 Total: 23683000000000006.16
J
<lang j>require 'numeric format/printf' hamburger_price=: 5.50 milkshake_price=: 2.96 tax_rate=: 0.0765
total_before_tax=: +/ 4 2 * hamburger_price , milkshake_price tax=: 0.01 round tax_rate * total_before_tax total=: total_before_tax + tax
(8!:0 total_before_tax, tax, total) printf~ noun define
Total before tax: %8s Tax: %8s Total: %8s
)</lang>
- Output:
Total before tax: 27.92 Tax: 2.14 Total: 30.06
Perl 6
No need for a special type in Perl 6, 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.)) <lang perl6>my $hamburger-price = 5.50; my $milkshake-price = 2.96; my $tax-rate = 0.0765;
my $total-before-tax = $hamburger-price * 4 + $milkshake-price * 2; my $tax = ($tax-rate * $total-before-tax).round(0.01); my $total = $total-before-tax + $tax;
say qq:to/END/;
Total before tax: $total-before-tax.fmt('%8s') Tax: $tax.fmt('%8s') Total: $total.fmt('%8s') END</lang>
- Output:
Total before tax: 27.92 Tax: 2.14 Total: 30.06
Python
This uses Pythons decimal module, (and some copying of names from the Perl 6 example).
<lang python>from decimal import Decimal as D
hamburger_price = D('5.50') milkshake_price = D('2.96') tax_rate = D('0.0765')
total_before_tax = hamburger_price * 4 + milkshake_price * 2 tax = D(round(tax_rate * total_before_tax, 2)) total = total_before_tax + tax
print(
Total before tax: %8s Tax: %8s Total: %8s
% tuple(round(x, 2) for x in (total_before_tax, tax, total)))</lang>
- Output:
Total before tax: 27.92 Tax: 2.14 Total: 30.06
REXX
without commas
Programming note: the tax rate can be expressed with or without a percent (%) suffix. <lang rexx>/*REXX pgm shows a method of computing the total price & tax for items. */ numeric digits 200 /*let's get ka-razy.*/ taxRate= 7.65 /*# is: nn or nn% */ if right(taxRate,1)\=='%' then taxRate=taxRate/100 /*handle plain tax#.*/ taxRate=strip(taxRate,,'%') /*strip % (if any).*/ item. =; items=0 /*zero out register.*/ item.1 = '4000000000000000 $5.50 hamburger' item.2 = ' 2 $2.86 milkshake' total=0
do j=1 while item.j\== /*calc. total & tax.*/ parse var item.j quantity price thing /*ring up an item. */ items=items+quantity /*tally the # items. */ price = translate(price,,'$') /*maybe scrub out $. */ subtotal = quantity * price /*calculate subtotal.*/ total = total + subtotal /*calc. running total*/ say right(quantity,20) left(thing,20) show$(subtotal) end /*j*/
say '────────────────────────────────────────────────────────────────' tax=format(total*taxRate,,2) /*round total tax for all items. */ say right(items "(items)",28) right('total=',12) show$(total) say right('tax at' (taxRate*100/1)"%=", 41) show$(tax) say right('grand total=', 41) show$(total+tax) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOW$ subroutine────────────────────*/ show$: return right('$' || arg(1),20) /*right-justify & format a $total*/</lang> output (attempting to mimic a check-out register to some degree):
4000000000000000 hamburger 22000000000000000.00 2 milkshake $5.72 ──────────────────────────────────────────────────────────────── 4000000000000002 (items) total= 22000000000000005.72 tax at 7.65%= $1683000000000000.44 grand total= 23683000000000006.16
with commas
Programming note: the comma REXX subroutine (below) is a heavy-duty version that can handle any kind of number (numbers may have leading signs, imbedded blanks (after the sign), and it also handles numbers with leading and/or trailing currency symbols, and also exponentiated numbers (of any type or style of exponent notation). It also can support any character (or characters) for the separator, as well as a specified period length (the default is 3 which indicates thousands separators). It can also limit the number of separators (normally a comma) to be inserted. <lang rexx>/*REXX pgm shows a method of computing the total price & tax for itemss */ numeric digits 200 /*let's get ka-razy.*/ taxRate= 7.65 /*# is: nn or nn% */ if right(taxRate,1)\=='%' then taxRate=taxRate/100 /*handle plain tax#.*/ taxRate=strip(taxRate,,'%') /*strip % (if any).*/ item. =; items=0 /*zero out register.*/ item.1 = '4000000000000000 $5.50 hamburger' item.2 = ' 2 $2.86 milkshake' total=0
do j=1 while item.j\== /*calc. total & tax.*/ parse var item.j quantity price thing /*ring up an item. */ items=items+quantity /*tally the # items. */ price = translate(price,,'$') /*maybe scrub out $. */ subtotal = quantity * price /*calculate subtotal.*/ total = total + subtotal /*calc. running total*/ say right(comma(quantity),24) left(thing,20) show$(subtotal) end /*j*/
say '═══════════════════════════════════════════════════════════════════════════' tax=format(total*taxRate,,2) /*round total tax for all items. */ say right(comma(items "(items)"),32) right('total=',12) show$(total) say right('tax at' (taxRate*100/1)"%=", 45) show$(tax) say right('grand total=', 45) show$(total+tax) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────COMMA subroutine────────────────────*/ comma: procedure; parse arg _,c,p,t; arg ,cu; c=word(c ",",1) if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1) if \datatype(p,'W') | \datatype(t,'W')|p==0|arg()>4 then return _; n=_'.9'
- =123456789; k=0; if o<0 then do; b=verify(_,' '); if b==0 then return _
e=length(_) - verify(reverse(_),' ') + 1; end; else do; b=verify(n,#,"M") e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end
do j=e to b by -p while k<t; _=insert(c,_,j); k=k+1; end; return _
/*──────────────────────────────────SHOW$ subroutine────────────────────*/ show$: return right(comma('$'||arg(1)),27) /*right-justify & format a #.*/</lang> output with commas in the larger numbers:
4,000,000,000,000,000 hamburger $22,000,000,000,000,000.00 2 milkshake $5.72 ═══════════════════════════════════════════════════════════════════════════ 4,000,000,000,000,002 (items) total= $22,000,000,000,000,005.72 tax at 7.65%= $1,683,000,000,000,000.44 grand total= $23,683,000,000,000,006.16
Tcl
<lang tcl>package require math::decimal namespace import math::decimal::*
set hamburgerPrice [fromstr 5.50] set milkshakePrice [fromstr 2.86] set taxRate [/ [fromstr 7.65] [fromstr 100]]
set burgers 4000000000000000 set shakes 2 set net [+ [* [fromstr $burgers] $hamburgerPrice] [* [fromstr $shakes] $milkshakePrice]] set tax [round_up [* $net $taxRate] 2] set total [+ $net $tax]
puts "net=[tostr $net], tax=[tostr $tax], total=[tostr $total]"</lang>
- Output:
net=22000000000000005.72, tax=1683000000000000.44, total=23683000000000006.16