Currency: Difference between revisions

Content added Content deleted
(→‎{{header|Lua}}: added Lua solution)
m (syntax highlighting fixup automation)
Line 40: Line 40:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F currency(units, subunits)
<syntaxhighlight lang="11l">F currency(units, subunits)
R BigInt(units) * 100 + subunits
R BigInt(units) * 100 + subunits


Line 63: Line 63:
print(‘Total price before tax: ’to_str(beforeTax).rjust(maxlen))
print(‘Total price before tax: ’to_str(beforeTax).rjust(maxlen))
print(‘Tax: ’to_str(tax).rjust(maxlen))
print(‘Tax: ’to_str(tax).rjust(maxlen))
print(‘Total with tax: ’to_str(total).rjust(maxlen))</lang>
print(‘Total with tax: ’to_str(total).rjust(maxlen))</syntaxhighlight>


{{out}}
{{out}}
Line 79: Line 79:
When using the Dollar_IO package to print each value, the constant is converted into a Dollar, then printed. All of
When using the Dollar_IO package to print each value, the constant is converted into a Dollar, then printed. All of
the arbitrary-precision arithmetic operations are done at compile-time, incurring no runtime cost.
the arbitrary-precision arithmetic operations are done at compile-time, incurring no runtime cost.
<lang ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Currency is
procedure Currency is
Line 104: Line 104:
Dollar_IO.Put(total_with_tax);
Dollar_IO.Put(total_with_tax);
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
end Currency;</lang>
end Currency;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 114: Line 114:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# currency calculations #
# currency calculations #
# simple fixed point type, LONG INT is 64-bit in Algol 68G #
# simple fixed point type, LONG INT is 64-bit in Algol 68G #
Line 178: Line 178:
print( ( "tax: ", TOSTRING tax, newline ) );
print( ( "tax: ", TOSTRING tax, newline ) );
print( ( "total: ", TOSTRING total, newline ) )
print( ( "total: ", TOSTRING total, newline ) )
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 190: Line 190:
The AppleScript core language doesn't recognise currency values specifically and its numbers don't have the precision required for this task, but through ASObjC, it's able to use Foundation classes which do.
The AppleScript core language doesn't recognise currency values specifically and its numbers don't have the precision required for this task, but through ASObjC, it's able to use Foundation classes which do.


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 242: Line 242:
{quantity:2, unitPrice:currencySymbol & 2.86}}
{quantity:2, unitPrice:currencySymbol & 2.86}}
set taxRate to 7.65
set taxRate to 7.65
return billTotal(quantitiesAndPrices, taxRate, currencySymbol)</lang>
return billTotal(quantitiesAndPrices, taxRate, currencySymbol)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"Subtotal: $22,000,000,000,000,005.72
<syntaxhighlight lang="applescript">"Subtotal: $22,000,000,000,000,005.72
Tax: $1,683,000,000,000,000.44
Tax: $1,683,000,000,000,000.44
Total: $23,683,000,000,000,006.16"</lang>
Total: $23,683,000,000,000,006.16"</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
===version 1===
===version 1===
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -M -f CURRENCY.AWK
# syntax: GAWK -M -f CURRENCY.AWK
# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)
# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)
Line 272: Line 272:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 284: Line 284:
</pre>
</pre>
===version 2===
===version 2===
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -M -f CURRENCY2.AWK
# syntax: GAWK -M -f CURRENCY2.AWK
# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)
# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)
Line 308: Line 308:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 322: Line 322:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
The amounts <code>before-tax</code>, <code>tax</code>, <code>after-tax</code> are computed as rounded amounts in dollar cents.
The amounts <code>before-tax</code>, <code>tax</code>, <code>after-tax</code> are computed as rounded amounts in dollar cents.
<lang bracmat> div$((4000000000000000*550+2*286)+1/2,1):?before-tax
<syntaxhighlight lang="bracmat"> div$((4000000000000000*550+2*286)+1/2,1):?before-tax
& div$(!before-tax*765/10000+1/2,1):?tax
& div$(!before-tax*765/10000+1/2,1):?tax
& !before-tax+!tax:?after-tax
& !before-tax+!tax:?after-tax
Line 343: Line 343:
fix$!after-tax
fix$!after-tax
\n
\n
)</lang>
)</syntaxhighlight>
''Output''
''Output''
<pre>before-tax 22000000000000005.72
<pre>before-tax 22000000000000005.72
Line 357: Line 357:
</pre>
</pre>
One remark about the code, notice that for setting all other variables the '''mpf_set_d''' function is used:
One remark about the code, notice that for setting all other variables the '''mpf_set_d''' function is used:
<syntaxhighlight lang="c">
<lang C>
mpf_set_d(burgerUnitPrice,5.50);
mpf_set_d(burgerUnitPrice,5.50);
mpf_set_d(milkshakePrice,2 * 2.86);
mpf_set_d(milkshakePrice,2 * 2.86);
mpf_set_d(burgerNum,4000000000000000);
mpf_set_d(burgerNum,4000000000000000);
mpf_set_d(milkshakeNum,2);
mpf_set_d(milkshakeNum,2);
</syntaxhighlight>
</lang>
But when it comes to the tax rate, it's '''mpf_set_str''':
But when it comes to the tax rate, it's '''mpf_set_str''':
<syntaxhighlight lang="c">
<lang C>
mpf_set_str(tax,"0.0765",10);
mpf_set_str(tax,"0.0765",10);
</syntaxhighlight>
</lang>
The reason is a weird rounding off error which happens if the mpf_set_d function is used. Documentation and example usages of GMP are very rare on the net possibly because it is used almost exclusively by academia and high tech industries. The implementation below is the result of a lot of fiddling, gotchas and lessons learnt, just how good programming should always be :)
The reason is a weird rounding off error which happens if the mpf_set_d function is used. Documentation and example usages of GMP are very rare on the net possibly because it is used almost exclusively by academia and high tech industries. The implementation below is the result of a lot of fiddling, gotchas and lessons learnt, just how good programming should always be :)
{{libheader|GMP}}
{{libheader|GMP}}
<syntaxhighlight lang="c">
<lang C>


#include<stdio.h>
#include<stdio.h>
Line 400: Line 400:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 410: Line 410:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
The built in C# type decimal has a max value of 79228162514264337593543950335.
The built in C# type decimal has a max value of 79228162514264337593543950335.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 464: Line 464:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Total before tax: $22,000,000,000,000,005.72
<pre>Total before tax: $22,000,000,000,000,005.72
Line 473: Line 473:
{{libheader|clojurewerkz/money}}
{{libheader|clojurewerkz/money}}


<lang clojure>(require '[clojurewerkz.money.amounts :as ma])
<syntaxhighlight lang="clojure">(require '[clojurewerkz.money.amounts :as ma])
(require '[clojurewerkz.money.currencies :as mc])
(require '[clojurewerkz.money.currencies :as mc])
(require '[clojurewerkz.money.format :as mf])
(require '[clojurewerkz.money.format :as mf])
Line 483: Line 483:
(println "Total before tax: " (mf/format pre-tax))
(println "Total before tax: " (mf/format pre-tax))
(println " Tax: " (mf/format tax))
(println " Tax: " (mf/format tax))
(println " Total with tax: " (mf/format (ma/plus pre-tax tax))))</lang>
(println " Total with tax: " (mf/format (ma/plus pre-tax tax))))</syntaxhighlight>


{{out}}
{{out}}
Line 493: Line 493:
{{libheader|io.randomseed/bankster}}
{{libheader|io.randomseed/bankster}}


<lang clojure>(require '[io.randomseed.bankster.money :as m])
<syntaxhighlight lang="clojure">(require '[io.randomseed.bankster.money :as m])


(let [burgers (m/mul #money[USD 5.50] 4000000000000000)
(let [burgers (m/mul #money[USD 5.50] 4000000000000000)
Line 501: Line 501:
(println "Total before tax: " (m/format pre-tax))
(println "Total before tax: " (m/format pre-tax))
(println " Tax: " (m/format tax))
(println " Tax: " (m/format tax))
(println " Total with tax: " (m/format (m/add pre-tax tax))))</lang>
(println " Total with tax: " (m/format (m/add pre-tax tax))))</syntaxhighlight>


{{out}}
{{out}}
Line 516: Line 516:
{{works with|GNU Cobol|2.1}}
{{works with|GNU Cobol|2.1}}


<lang cobol> >>SOURCE FREE
<syntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. currency-example.
PROGRAM-ID. currency-example.
Line 543: Line 543:
DISPLAY " Total with tax: " total-edited
DISPLAY " Total with tax: " total-edited
.
.
END PROGRAM currency-example.</lang>
END PROGRAM currency-example.</syntaxhighlight>


{{out}}
{{out}}
Line 558: Line 558:
{{libheader| Velthuis.BigIntegers}}
{{libheader| Velthuis.BigIntegers}}
{{Trans|Go}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Currency;
program Currency;


Line 693: Line 693:
Writeln(' Total: ', total.ToString: 22);
Writeln(' Total: ', total.ToString: 22);
readln;
readln;
end.</lang>
end.</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let hamburgers = 4000000000000000M
let hamburgers = 4000000000000000M
Line 710: Line 710:
printfn "Total before tax:\t$%M" <| Math.Round (total, 2)
printfn "Total before tax:\t$%M" <| Math.Round (total, 2)
printfn " Tax:\t$%M" <| Math.Round (tax, 2)
printfn " Tax:\t$%M" <| Math.Round (tax, 2)
printfn " Total:\t$%M" <| Math.Round (totalWithTax, 2)</lang>
printfn " Total:\t$%M" <| Math.Round (totalWithTax, 2)</syntaxhighlight>


{{out}}
{{out}}
Line 722: Line 722:
=={{header|Factor}}==
=={{header|Factor}}==
Factor's <tt>ratio</tt> type can handle arbitrary-precision calculations with rational numbers. The <tt>money</tt> vocabulary implements convenience words for treating rationals as money. The <tt>DECIMAL:</tt> parsing word is used to convert the tax rate <tt>0.0765</tt> to a ratio <tt>153/2000</tt>. The <tt>money.</tt> word is used to print the subtotal <tt>22000000000000005+18/25</tt>, tax <tt>1683000000000000+21879/50000</tt>, and total <tt>23683000000000006+7879/50000</tt> formatted as you would expect.
Factor's <tt>ratio</tt> type can handle arbitrary-precision calculations with rational numbers. The <tt>money</tt> vocabulary implements convenience words for treating rationals as money. The <tt>DECIMAL:</tt> parsing word is used to convert the tax rate <tt>0.0765</tt> to a ratio <tt>153/2000</tt>. The <tt>money.</tt> word is used to print the subtotal <tt>22000000000000005+18/25</tt>, tax <tt>1683000000000000+21879/50000</tt>, and total <tt>23683000000000006+7879/50000</tt> formatted as you would expect.
<lang factor>USING: combinators.smart io kernel math math.functions money ;
<syntaxhighlight lang="factor">USING: combinators.smart io kernel math math.functions money ;


10 15 ^ 4 * 5+50/100 * ! hamburger subtotal
10 15 ^ 4 * 5+50/100 * ! hamburger subtotal
Line 732: Line 732:
"Total before tax: " write [ money. ] 2dip
"Total before tax: " write [ money. ] 2dip
"Tax: " write [ money. ] dip
"Tax: " write [ money. ] dip
"Total with tax: " write money.</lang>
"Total with tax: " write money.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 743: Line 743:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Pero el subtotal y el tax los muestra redondeados. Y no encuentro el porqué.
Pero el subtotal y el tax los muestra redondeados. Y no encuentro el porqué.
<lang freebasic>Dim As Longint hamburger_p = 550
<syntaxhighlight lang="freebasic">Dim As Longint hamburger_p = 550
Dim As Longint hamburger_q = 4000000000000000
Dim As Longint hamburger_q = 4000000000000000
Dim As Longint hamburger_v = hamburger_p * hamburger_q
Dim As Longint hamburger_v = hamburger_p * hamburger_q
Line 758: Line 758:
Print Using " tax #####################.##";tax/100
Print Using " tax #####################.##";tax/100
Print Using " total #####################.##";subtotal/10+tax/100
Print Using " total #####################.##";subtotal/10+tax/100
Sleep</lang>
Sleep</syntaxhighlight>




Line 764: Line 764:
Frink tracks units of measure through all calculations, so you can specify quantities as "dollar", "cent", etc.
Frink tracks units of measure through all calculations, so you can specify quantities as "dollar", "cent", etc.


<lang frink>
<syntaxhighlight lang="frink">
st = 4000000000000000 * 5.50 dollars + 2 * 2.86 dollars
st = 4000000000000000 * 5.50 dollars + 2 * 2.86 dollars
tax = round[st * 7.65 percent, cent]
tax = round[st * 7.65 percent, cent]
Line 771: Line 771:
println["Tax: " + format[tax, "dollars", 2]]
println["Tax: " + format[tax, "dollars", 2]]
println["Total: " + format[total, "dollars", 2]]
println["Total: " + format[total, "dollars", 2]]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 780: Line 780:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 867: Line 867:
fmt.Printf(" Tax: %22s\n", tax)
fmt.Printf(" Tax: %22s\n", tax)
fmt.Printf(" Total: %22s\n", total)
fmt.Printf(" Total: %22s\n", total)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 876: Line 876:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.Fixed
<syntaxhighlight lang="haskell">import Data.Fixed
import Text.Printf
import Text.Printf


Line 895: Line 895:
printAmount "Subtotal" subtotal
printAmount "Subtotal" subtotal
printAmount "Tax" tx
printAmount "Tax" tx
printAmount "Total" total</lang>
printAmount "Total" total</syntaxhighlight>


{{out}}
{{out}}
Line 909: Line 909:
We use a naive implementation with arbitrary precision (rational) numbers:
We use a naive implementation with arbitrary precision (rational) numbers:


<lang j>require 'format/printf'
<syntaxhighlight lang="j">require 'format/printf'
Items=: ;: 'Hamburger Milkshake'
Items=: ;: 'Hamburger Milkshake'
Line 929: Line 929:
)
)


makeBill Items;Prices;Quantities</lang>
makeBill Items;Prices;Quantities</syntaxhighlight>
{{out}}
{{out}}
<pre> Item Price Quantity Value
<pre> Item Price Quantity Value
Line 942: Line 942:


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.math.*;
<syntaxhighlight lang="java">import java.math.*;
import java.util.*;
import java.util.*;


Line 980: Line 980:
System.out.printf(" Total: %20.2f%n", subtotal.add(tax));
System.out.printf(" Total: %20.2f%n", subtotal.add(tax));
}
}
}</lang>
}</syntaxhighlight>


<pre>Subtotal: 22000000000000005.72
<pre>Subtotal: 22000000000000005.72
Line 987: Line 987:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>const money = require('money-math')
<syntaxhighlight lang="javascript">const money = require('money-math')


let hamburgers = 4000000000000000
let hamburgers = 4000000000000000
Line 1,011: Line 1,011:
console.log('Tax:', taxTotal)
console.log('Tax:', taxTotal)
console.log('Total:', total)
console.log('Total:', total)
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 1,024: Line 1,024:
results as dollars and cents, and when calculating the taxes.
results as dollars and cents, and when calculating the taxes.


<lang jq>def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
<syntaxhighlight lang="jq">def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;


# print as dollars and cents
# print as dollars and cents
Line 1,067: Line 1,067:
" Total before tax: \($before_tax | dollars($width))",
" Total before tax: \($before_tax | dollars($width))",
" - tax: \($taxes | cents | dollars($width))",
" - tax: \($taxes | cents | dollars($width))",
" Total after tax: \($after_tax | dollars($width))"</lang>
" Total after tax: \($after_tax | dollars($width))"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,078: Line 1,078:
{{works with|Julia|1.2}}
{{works with|Julia|1.2}}


<lang julia>using Printf
<syntaxhighlight lang="julia">using Printf


p = [big"5.50", big"2.86"]
p = [big"5.50", big"2.86"]
Line 1,090: Line 1,090:
@printf " - tot. before tax: %20.2f \$\n" beftax
@printf " - tot. before tax: %20.2f \$\n" beftax
@printf " - tax: %20.2f \$\n" tax
@printf " - tax: %20.2f \$\n" tax
@printf " - tot. after tax: %20.2f \$\n" afttax</lang>
@printf " - tot. after tax: %20.2f \$\n" afttax</syntaxhighlight>


{{out}}
{{out}}
Line 1,098: Line 1,098:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.math.BigDecimal
import java.math.BigDecimal
Line 1,116: Line 1,116:
println("Tax thereon @ 7.65% : ${fmt.format(tax)}")
println("Tax thereon @ 7.65% : ${fmt.format(tax)}")
println("Total price after tax : ${fmt.format(price + tax)}")
println("Total price after tax : ${fmt.format(price + tax)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,127: Line 1,127:
=={{header|Lua}}==
=={{header|Lua}}==
Using the lbc library for arbitrary precision support.
Using the lbc library for arbitrary precision support.
<lang lua>C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end})
<syntaxhighlight lang="lua">C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end})
C.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes
C.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes


Line 1,136: Line 1,136:
print(("Before tax: %20s"):format(subtot:tostring()))
print(("Before tax: %20s"):format(subtot:tostring()))
print(("Tax : %20s"):format(tax:tostring()))
print(("Tax : %20s"):format(tax:tostring()))
print(("With tax : %20s"):format(total:tostring()))</lang>
print(("With tax : %20s"):format(total:tostring()))</syntaxhighlight>
{{out}}
{{out}}
<pre>Before tax: 22000000000000005.72
<pre>Before tax: 22000000000000005.72
Line 1,144: Line 1,144:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
This task written in M2000 Environment running on Wine 3.6, in a Linux Ubuntu Studio. M2000 environment is an ActiveX object, written with VB6, which use many types from [https://en.wikipedia.org/wiki/Variant_type COM Variant Type].
This task written in M2000 Environment running on Wine 3.6, in a Linux Ubuntu Studio. M2000 environment is an ActiveX object, written with VB6, which use many types from [https://en.wikipedia.org/wiki/Variant_type COM Variant Type].
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Currency_Task {
Module Currency_Task {
Locale 1033
Locale 1033
Line 1,210: Line 1,210:
}
}
Currency_Task
Currency_Task
</syntaxhighlight>
</lang>
Optional with $ and thousands separator (a smaller version from above)
Optional with $ and thousands separator (a smaller version from above)
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Currency_Task {
Module Currency_Task {
Locale 1033
Locale 1033
Line 1,255: Line 1,255:
}
}
Currency_Task
Currency_Task
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 1,275: Line 1,275:


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>


Digits := 50;
Digits := 50;
Line 1,296: Line 1,296:
totalprice := totaltax + total;
totalprice := totaltax + total;
printf("%.2f\n",totalprice);
printf("%.2f\n",totalprice);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,305: Line 1,305:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>total = 4000000000000000 Rationalize[5.50] + 2 Rationalize[2.86];
<syntaxhighlight lang="mathematica">total = 4000000000000000 Rationalize[5.50] + 2 Rationalize[2.86];
AccountingForm[N[total, 20], {\[Infinity], 2}]
AccountingForm[N[total, 20], {\[Infinity], 2}]
tax = total Rationalize[0.0765];
tax = total Rationalize[0.0765];
AccountingForm[N[tax, 20], {\[Infinity], 2}]
AccountingForm[N[tax, 20], {\[Infinity], 2}]
AccountingForm[N[total + tax, 20], {\[Infinity], 2}]</lang>
AccountingForm[N[total + tax, 20], {\[Infinity], 2}]</syntaxhighlight>
{{out}}
{{out}}
<pre>22000000000000005.72
<pre>22000000000000005.72
Line 1,320: Line 1,320:
Nim doesn’t provide a standard module to deal with decimal values. There exist some third party modules but we have chosen to use the “bignum” library which provides big integers and big rationals.
Nim doesn’t provide a standard module to deal with decimal values. There exist some third party modules but we have chosen to use the “bignum” library which provides big integers and big rationals.


<lang Nim>import strutils
<syntaxhighlight lang="nim">import strutils
import bignum
import bignum


Line 1,413: Line 1,413:
echo "Total price before tax: ", beforeTaxStr.align(length)
echo "Total price before tax: ", beforeTaxStr.align(length)
echo "Tax: ", taxStr.align(length)
echo "Tax: ", taxStr.align(length)
echo "Total with tax: ", totalStr.align(length)</lang>
echo "Total with tax: ", totalStr.align(length)</syntaxhighlight>


{{out}}
{{out}}
Line 1,424: Line 1,424:
Using the [https://github.com/janestreet/bignum Bignum] library.
Using the [https://github.com/janestreet/bignum Bignum] library.


<lang ocaml>#require "bignum" ;;
<syntaxhighlight lang="ocaml">#require "bignum" ;;


let p1 = Bignum.((of_string "4000000000000000") * (of_float_decimal 5.50)) ;;
let p1 = Bignum.((of_string "4000000000000000") * (of_float_decimal 5.50)) ;;
Line 1,441: Line 1,441:
Printf.printf "tax: %s\n" (my_to_string r2);
Printf.printf "tax: %s\n" (my_to_string r2);
Printf.printf "total: %s\n" (my_to_string r3);
Printf.printf "total: %s\n" (my_to_string r3);
;;</lang>
;;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,454: Line 1,454:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use Math::Decimal qw(dec_canonise dec_add dec_mul dec_rndiv_and_rem);
<syntaxhighlight lang="perl">use Math::Decimal qw(dec_canonise dec_add dec_mul dec_rndiv_and_rem);


@check = (
@check = (
Line 1,485: Line 1,485:
($q, $r) = dec_rndiv_and_rem("FLR", @_[0], 1);
($q, $r) = dec_rndiv_and_rem("FLR", @_[0], 1);
$q . substr((sprintf "%.2f", $r), 1, 3);
$q . substr((sprintf "%.2f", $r), 1, 3);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Item Price Quantity Extension
<pre>Item Price Quantity Extension
Line 1,497: Line 1,497:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] has been renamed)</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] has been renamed)</span>
Line 1,516: Line 1,516:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Tax:%21s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Tax:%21s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Total:%21s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Total:%21s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,525: Line 1,525:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang>(scl 2)
<syntaxhighlight lang="text">(scl 2)
(let
(let
(Before
(Before
Line 1,536: Line 1,536:
(tab Fmt "Total before tax:" (format Before *Scl "." ","))
(tab Fmt "Total before tax:" (format Before *Scl "." ","))
(tab Fmt "Tax:" (format Tax *Scl "." ","))
(tab Fmt "Tax:" (format Tax *Scl "." ","))
(tab Fmt "Total:" (format Total *Scl "." ",")) )</lang>
(tab Fmt "Total:" (format Total *Scl "." ",")) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,548: Line 1,548:
(and some copying of names from the Raku example).
(and some copying of names from the Raku example).


<lang python>from decimal import Decimal as D
<syntaxhighlight lang="python">from decimal import Decimal as D
from collections import namedtuple
from collections import namedtuple


Line 1,573: Line 1,573:
total = total_before_tax + tax
total = total_before_tax + tax
print(fmt % ('', '', '', '--------------------'))
print(fmt % ('', '', '', '--------------------'))
print(fmt % ('', '', 'Total', total))</lang>
print(fmt % ('', '', 'Total', total))</syntaxhighlight>


{{out}}
{{out}}
Line 1,592: Line 1,592:
The main problem is rounding correctly and this part is handled in cents-*, that implements a multiplication that rounds to the cents.
The main problem is rounding correctly and this part is handled in cents-*, that implements a multiplication that rounds to the cents.
The rest of the program is only formatting.
The rest of the program is only formatting.
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (cents-* x y)
(define (cents-* x y)
(/ (round (* 100 x y)) 100))
(/ (round (* 100 x y)) 100))
Line 1,636: Line 1,636:
(for-each show-item all)
(for-each show-item all)
(newline)
(newline)
(show-total all (/ #e7.65 100))</lang>
(show-total all (/ #e7.65 100))</syntaxhighlight>
{{out}}
{{out}}
<pre>hamburger 4000000000000000 $5.50 -> $22000000000000000.00
<pre>hamburger 4000000000000000 $5.50 -> $22000000000000000.00
Line 1,651: Line 1,651:
(In order to achieve imprecision, you have to explicitly use scientific notation,
(In order to achieve imprecision, you have to explicitly use scientific notation,
or use the <tt>Num</tt> type, or calculate a result that requires a denominator in excess of <tt>2 ** 64</tt>. (There's no limit on the numerator.))
or use the <tt>Num</tt> type, or calculate a result that requires a denominator in excess of <tt>2 ** 64</tt>. (There's no limit on the numerator.))
<lang perl6>my @check = q:to/END/.lines.map: { [.split(/\s+/)] };
<syntaxhighlight lang="raku" line>my @check = q:to/END/.lines.map: { [.split(/\s+/)] };
Hamburger 5.50 4000000000000000
Hamburger 5.50 4000000000000000
Milkshake 2.86 2
Milkshake 2.86 2
Line 1,678: Line 1,678:


# make up for lack of a Rat fixed-point printf format
# make up for lack of a Rat fixed-point printf format
sub fix2($x) { ($x + 0.001).subst(/ <?after \.\d\d> .* $ /, '') }</lang>
sub fix2($x) { ($x + 0.001).subst(/ <?after \.\d\d> .* $ /, '') }</syntaxhighlight>
{{out}}
{{out}}
<pre>Item Price Quantity Extension
<pre>Item Price Quantity Extension
Line 1,695: Line 1,695:
Programming note: &nbsp; the tax rate can be expressed with or without a percent &nbsp; ('''%''')&nbsp; suffix.
Programming note: &nbsp; the tax rate can be expressed with or without a percent &nbsp; ('''%''')&nbsp; suffix.
===without commas===
===without commas===
<lang rexx>/*REXX program shows a method of computing the total price and tax for purchased items.*/
<syntaxhighlight lang="rexx">/*REXX program shows a method of computing the total price and tax for purchased items.*/
numeric digits 200 /*support for gihugic numbers.*/
numeric digits 200 /*support for gihugic numbers.*/
taxRate= 7.65 /*number is: nn or nn% */
taxRate= 7.65 /*number is: nn or nn% */
Line 1,723: Line 1,723:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show$: return right( '$'arg(1), 27) /*right─justify and format a number. */</lang>
show$: return right( '$'arg(1), 27) /*right─justify and format a number. */</syntaxhighlight>
{{out|output|text=&nbsp; (attempting to mimic a check-out register to some degree):}}
{{out|output|text=&nbsp; (attempting to mimic a check-out register to some degree):}}
<pre>
<pre>
Line 1,739: Line 1,739:


===with commas===
===with commas===
<lang rexx>/*REXX program shows a method of computing the total price and tax for purchased items.*/
<syntaxhighlight lang="rexx">/*REXX program shows a method of computing the total price and tax for purchased items.*/
numeric digits 200 /*support for gihugic numbers.*/
numeric digits 200 /*support for gihugic numbers.*/
taxRate= 7.65 /*number is: nn or nn% */
taxRate= 7.65 /*number is: nn or nn% */
Line 1,771: Line 1,771:
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show$: return right( commas( '$'arg(1) ), 27) /*right─justify and format a number. */</lang>
show$: return right( commas( '$'arg(1) ), 27) /*right─justify and format a number. */</syntaxhighlight>
{{out|output|text=&nbsp; with commas in the larger numbers:}}
{{out|output|text=&nbsp; with commas in the larger numbers:}}
<pre>
<pre>
Line 1,787: Line 1,787:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Currency
# Project : Currency


Line 1,800: Line 1,800:
see "tax thereon @ 7.65 : " + tax + nl
see "tax thereon @ 7.65 : " + tax + nl
see "total price after tax : " + (price + tax) + nl
see "total price after tax : " + (price + tax) + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,808: Line 1,808:
</pre>
</pre>
=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'bigdecimal/util'
<syntaxhighlight lang="ruby">require 'bigdecimal/util'


before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d
before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d
Line 1,817: Line 1,817:
Tax: $#{tax.to_s('F')}
Tax: $#{tax.to_s('F')}
Total: $#{total.to_s('F')}"
Total: $#{total.to_s('F')}"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Before tax: $22000000000000005.72
<pre>Before tax: $22000000000000005.72
Line 1,826: Line 1,826:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>extern crate num_bigint; // 0.3.0
<syntaxhighlight lang="rust">extern crate num_bigint; // 0.3.0
extern crate num_rational; // 0.3.0
extern crate num_rational; // 0.3.0


Line 1,896: Line 1,896:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,907: Line 1,907:


{{libheader|Scala}}Locale is manipulated to demonstrate the behavior with other currencies.
{{libheader|Scala}}Locale is manipulated to demonstrate the behavior with other currencies.
<lang scala>import java.text.NumberFormat
<syntaxhighlight lang="scala">import java.text.NumberFormat
import java.util.Locale
import java.util.Locale


Line 1,936: Line 1,936:
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + f"${tax * 100}%5.2f%% tax" + '\t'}$taxation%,25.2f")
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + f"${tax * 100}%5.2f%% tax" + '\t'}$taxation%,25.2f")
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + "Amount due" + '\t'}${beforeTax + taxation}%,25.2f")
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + "Amount due" + '\t'}${beforeTax + taxation}%,25.2f")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
4000000000000000 Hamburger XL руб. 5,50 22 000 000 000 000 000,00
4000000000000000 Hamburger XL руб. 5,50 22 000 000 000 000 000,00
Line 1,948: Line 1,948:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>struct Item {
<syntaxhighlight lang="ruby">struct Item {
name, price, quant
name, price, quant
}
}
Line 1,975: Line 1,975:


var total = subtotal+tax
var total = subtotal+tax
printf(fmt, '', '', 'Total ', total)</lang>
printf(fmt, '', '', 'Total ', total)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,990: Line 1,990:
Using ScaledDecimal numbers ('sX'-suffix).
Using ScaledDecimal numbers ('sX'-suffix).
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>check := #(
<syntaxhighlight lang="smalltalk">check := #(
" amount name price "
" amount name price "
(4000000000000000 'hamburger' 5.50s2 )
(4000000000000000 'hamburger' 5.50s2 )
Line 2,024: Line 2,024:
Transcript printf:fmt withAll:{'' . '' . 'Total' . (totalSum+totalTax)}.
Transcript printf:fmt withAll:{'' . '' . 'Total' . (totalSum+totalTax)}.


Transcript cr; printCR:('Enjoy your Meal & Thank You for Dining at Milliways')</lang>
Transcript cr; printCR:('Enjoy your Meal & Thank You for Dining at Milliways')</syntaxhighlight>
{{out}}
{{out}}
<pre>Item Price Qty Extension
<pre>Item Price Qty Extension
Line 2,039: Line 2,039:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


extension Decimal {
extension Decimal {
Line 2,057: Line 2,057:
print("Price before tax: $\(totalBeforeTax)")
print("Price before tax: $\(totalBeforeTax)")
print("Total tax to be collected: $\(taxesToBeCollected)")
print("Total tax to be collected: $\(taxesToBeCollected)")
print("Total with taxes: $\(totalBeforeTax + taxesToBeCollected)")</lang>
print("Total with taxes: $\(totalBeforeTax + taxesToBeCollected)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,066: Line 2,066:


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|math::decimal}}<lang tcl>package require math::decimal
{{tcllib|math::decimal}}<syntaxhighlight lang="tcl">package require math::decimal
namespace import math::decimal::*
namespace import math::decimal::*


Line 2,079: Line 2,079:
set total [+ $net $tax]
set total [+ $net $tax]


puts "net=[tostr $net], tax=[tostr $tax], total=[tostr $total]"</lang>
puts "net=[tostr $net], tax=[tostr $tax], total=[tostr $total]"</syntaxhighlight>
{{out}}
{{out}}
net=22000000000000005.72, tax=1683000000000000.44, total=23683000000000006.16
net=22000000000000005.72, tax=1683000000000000.44, total=23683000000000006.16
Line 2,085: Line 2,085:
=={{header|VBA}}==
=={{header|VBA}}==
Used in locality Euroland. Formatting as currency shows € in stead of $, and thousand separators are "." in stead of "," and the decimail 'point' is "," in stead of "." When run in the USA it will be with dollar sign and so on.
Used in locality Euroland. Formatting as currency shows € in stead of $, and thousand separators are "." in stead of "," and the decimail 'point' is "," in stead of "." When run in the USA it will be with dollar sign and so on.
<lang vb>Public Sub currency_task()
<syntaxhighlight lang="vb">Public Sub currency_task()
'4000000000000000 hamburgers at $5.50 each
'4000000000000000 hamburgers at $5.50 each
Dim number_of_hamburgers As Variant
Dim number_of_hamburgers As Variant
Line 2,110: Line 2,110:
'the total with tax
'the total with tax
Debug.Print "Total with tax "; Format(total_price_before_tax + tax, "Currency")
Debug.Print "Total with tax "; Format(total_price_before_tax + tax, "Currency")
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>Total price before tax € 22.000.000.000.000.005,72
<pre>Total price before tax € 22.000.000.000.000.005,72
Tax € 1.683.000.000.000.000,44
Tax € 1.683.000.000.000.000,44
Line 2,117: Line 2,117:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<lang ecmascript>import "/big" for BigRat
<syntaxhighlight lang="ecmascript">import "/big" for BigRat


var hamburgers = BigRat.new("4000000000000000")
var hamburgers = BigRat.new("4000000000000000")
Line 2,130: Line 2,130:
System.print("Total price before tax : %((totalPreTax).toDecimal(2))")
System.print("Total price before tax : %((totalPreTax).toDecimal(2))")
System.print("Tax : %((totalTax).toDecimal(2))")
System.print("Tax : %((totalTax).toDecimal(2))")
System.print("Total price after tax : %((totalAfterTax).toDecimal(2))")</lang>
System.print("Total price after tax : %((totalAfterTax).toDecimal(2))")</syntaxhighlight>


{{out}}
{{out}}
Line 2,143: Line 2,143:
So, just multiply bucks by 100 and be careful when doing tax calculations.
So, just multiply bucks by 100 and be careful when doing tax calculations.
{{trans|Python}}
{{trans|Python}}
<lang zkl>var priceList=Dictionary("hamburger",550, "milkshake",286);
<syntaxhighlight lang="zkl">var priceList=Dictionary("hamburger",550, "milkshake",286);
var taxRate=765; // percent*M
var taxRate=765; // percent*M
const M=0d10_000;
const M=0d10_000;
Line 2,168: Line 2,168:
fmt.fmt("","","","--------------------").println();
fmt.fmt("","","","--------------------").println();
fmt.fmt("","","Total",toBucks(totalBeforeTax + tax)).println();
fmt.fmt("","","Total",toBucks(totalBeforeTax + tax)).println();
}</lang>
}</syntaxhighlight>
<lang zkl>calcTab(T("milkshake",2),T("hamburger",4000000000000000));</lang>
<syntaxhighlight lang="zkl">calcTab(T("milkshake",2),T("hamburger",4000000000000000));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>