Currency: Difference between revisions
added RPL
(added RPL) |
|||
(25 intermediate revisions by 13 users not shown) | |||
Line 36:
Dollar signs and thousands separators are optional.
<br><br>
=={{header|11l}}==
{{trans|Nim}}
<syntaxhighlight lang="11l">F currency(units, subunits)
R BigInt(units) * 100 + subunits
F currency_from_str(s)
V (units, subunits) = s.split(‘.’)
R BigInt(units) * 100 + Int(subunits)
F percentage(a, num, denom)
R (a * num * 10 I/ denom + 5) I/ 10
F to_str(c)
R String(c I/ 100)‘’‘.#02’.format(c % 100)
V hamburgers = currency(5, 50) * 4'000'000'000'000'000
V milkshakes = currency_from_str(‘2.86’) * 2
V beforeTax = hamburgers + milkshakes
V tax = percentage(beforeTax, 765, 10'000)
V total = beforeTax + tax
V maxlen = max(to_str(beforeTax).len, to_str(tax).len, to_str(total).len)
print(‘Total price before tax: ’to_str(beforeTax).rjust(maxlen))
print(‘Tax: ’to_str(tax).rjust(maxlen))
print(‘Total with tax: ’to_str(total).rjust(maxlen))</syntaxhighlight>
{{out}}
<pre>
Total price before tax: 22000000000000005.72
Tax: 1683000000000000.44
Total with tax: 23683000000000006.16
</pre>
=={{header|Ada}}==
Line 44 ⟶ 79:
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.
<
procedure Currency is
Line 69 ⟶ 104:
Dollar_IO.Put(total_with_tax);
Ada.Text_IO.New_Line;
end Currency;</
{{out}}
<pre>
Line 79 ⟶ 114:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<
# currency calculations #
# simple fixed point type, LONG INT is 64-bit in Algol 68G #
Line 143 ⟶ 178:
print( ( "tax: ", TOSTRING tax, newline ) );
print( ( "total: ", TOSTRING total, newline ) )
END</
{{out}}
<pre>
Line 155 ⟶ 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.
<
use framework "Foundation"
Line 207 ⟶ 242:
{quantity:2, unitPrice:currencySymbol & 2.86}}
set taxRate to 7.65
return billTotal(quantitiesAndPrices, taxRate, currencySymbol)</
{{output}}
<
Tax: $1,683,000,000,000,000.44
Total: $23,683,000,000,000,006.16"</
=={{header|AWK}}==
===version 1===
<syntaxhighlight lang="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)
Line 237 ⟶ 272:
exit(0)
}
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 249 ⟶ 284:
</pre>
===version 2===
<syntaxhighlight lang="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)
Line 273 ⟶ 308:
exit(0)
}
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 284 ⟶ 319:
total 23683000000000006.16
</pre>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> REM No need for BigNum library.
REM This language uses 80bit (10 bytes!) for real values internally.
Price = 4E15 * 5.50 + 2.0 * 2.86
Tax = Price * .0765
Total = Price + Tax
REM Number printing will use 2 decimal places and 21 positions zone
@%=&020215
PRINT "Price = $" Price
PRINT "Tax = $" Tax
PRINT "Total = $" Total</syntaxhighlight>
{{out}}
<pre>Price = $ 22000000000000005.72
Tax = $ 1683000000000000.44
Total = $ 23683000000000006.16</pre>
=={{header|Bracmat}}==
The amounts <code>before-tax</code>, <code>tax</code>, <code>after-tax</code> are computed as rounded amounts in dollar cents.
<
& div$(!before-tax*765/10000+1/2,1):?tax
& !before-tax+!tax:?after-tax
Line 308 ⟶ 360:
fix$!after-tax
\n
)</
''Output''
<pre>before-tax 22000000000000005.72
Line 322 ⟶ 374:
</pre>
One remark about the code, notice that for setting all other variables the '''mpf_set_d''' function is used:
<syntaxhighlight lang="c">
mpf_set_d(burgerUnitPrice,5.50);
mpf_set_d(milkshakePrice,2 * 2.86);
mpf_set_d(burgerNum,4000000000000000);
mpf_set_d(milkshakeNum,2);
</syntaxhighlight>
But when it comes to the tax rate, it's '''mpf_set_str''':
<syntaxhighlight lang="c">
mpf_set_str(tax,"0.0765",10);
</syntaxhighlight>
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}}
<syntaxhighlight lang="c">
#include<stdio.h>
Line 365 ⟶ 417:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 373 ⟶ 425:
</pre>
=={{header|C sharp|C#}}==
The built in C# type decimal has a max value of 79228162514264337593543950335.
<
using System.Collections.Generic;
Line 429 ⟶ 481:
}
}
}</
{{out}}
<pre>Total before tax: $22,000,000,000,000,005.72
Line 438 ⟶ 490:
{{libheader|clojurewerkz/money}}
<
(require '[clojurewerkz.money.currencies :as mc])
(require '[clojurewerkz.money.format :as mf])
Line 448 ⟶ 500:
(println "Total before tax: " (mf/format pre-tax))
(println " Tax: " (mf/format tax))
(println " Total with tax: " (mf/format (ma/plus pre-tax tax))))</
{{out}}
Line 458 ⟶ 510:
{{libheader|io.randomseed/bankster}}
<
(let [burgers (m/mul #money[USD 5.50] 4000000000000000)
Line 466 ⟶ 518:
(println "Total before tax: " (m/format pre-tax))
(println " Tax: " (m/format tax))
(println " Total with tax: " (m/format (m/add pre-tax tax))))</
{{out}}
Line 481 ⟶ 533:
{{works with|GNU Cobol|2.1}}
<
IDENTIFICATION DIVISION.
PROGRAM-ID. currency-example.
Line 508 ⟶ 560:
DISPLAY " Total with tax: " total-edited
.
END PROGRAM currency-example.</
{{out}}
Line 517 ⟶ 569:
Total with tax: $23683000000000006.16
</pre>
=={{header|Common Lisp}}==
Let us just use the built-in and convenient rationals (which use two bignums for numerator and denominator).
<syntaxhighlight lang="lisp">(defun print-$ (rat &key (prefix "") (stream t))
(multiple-value-bind (dollars cents) (truncate rat)
(format stream "~A~D.~D~%" prefix dollars (round (* 100 cents)))))
(defun compute-check (order-alist tax-rate)
(let* ((total-before-tax
(loop :for (amount . price) in order-alist
:sum (* (rationalize price) amount)))
(tax (* (rationalize tax-rate) total-before-tax)))
(print-$ total-before-tax :prefix "Total before tax: ")
(print-$ tax :prefix "Tax: ")
(print-$ (+ total-before-tax tax) :prefix "Total with tax: ")))
(compute-check '((4000000000000000 . 5.5) (2 . 2.86)) 0.0765)</syntaxhighlight>
{{out}}
<pre>Total before tax: 22000000000000005.72
Tax: 1683000000000000.44
Total with tax: 23683000000000006.16</pre>
A reader macro can be used as extra nice icing on the cake:
<syntaxhighlight lang="lisp">(defun read-$ (stream char)
(declare (ignore char))
(let* ((str (with-output-to-string (out)
;; TODO: read integer, if dot, read dot and another integer
(loop :for next = (peek-char nil stream t nil t)
:while (or (digit-char-p next) (char= next #\.))
:do (write-char (read-char stream t nil t) out))))
(dot-pos (position #\. str))
(dollars (parse-integer str :end dot-pos))
(cents (if dot-pos
(/ (parse-integer str :start (+ dot-pos 1))
(expt 10 (- (length str) (+ dot-pos 1))))
0)))
(+ dollars cents)))
(set-macro-character #\$ #'read-$ t)
(defun print-$ (rat &key (prefix "") (stream t))
(multiple-value-bind (dollars cents) (truncate rat)
(format stream "~A~D.~D~%" prefix dollars (round (* 100 cents)))))
(defun compute-check (order-alist tax-rate)
(let* ((total-before-tax
(loop :for (amount . price) in order-alist
:sum (* price amount)))
(tax (* (rationalize tax-rate) total-before-tax)))
(print-$ total-before-tax :prefix "Total before tax: ")
(print-$ tax :prefix "Tax: ")
(print-$ (+ total-before-tax tax) :prefix "Total with tax: ")))
(compute-check '((4000000000000000 . $5.5) (2 . $2.86)) 0.0765)</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
Line 523 ⟶ 631:
{{libheader| Velthuis.BigIntegers}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Currency;
Line 658 ⟶ 766:
Writeln(' Total: ', total.ToString: 22);
readln;
end.</
=={{header|F_Sharp|F#}}==
<
let hamburgers = 4000000000000000M
Line 675 ⟶ 783:
printfn "Total before tax:\t$%M" <| Math.Round (total, 2)
printfn " Tax:\t$%M" <| Math.Round (tax, 2)
printfn " Total:\t$%M" <| Math.Round (totalWithTax, 2)</
{{out}}
Line 687 ⟶ 795:
=={{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.
<
10 15 ^ 4 * 5+50/100 * ! hamburger subtotal
Line 697 ⟶ 805:
"Total before tax: " write [ money. ] 2dip
"Tax: " write [ money. ] dip
"Total with tax: " write money.</
{{out}}
<pre>
Line 708 ⟶ 816:
=={{header|FreeBASIC}}==
Pero el subtotal y el tax los muestra redondeados. Y no encuentro el porqué.
<
Dim As Longint hamburger_q = 4000000000000000
Dim As Longint hamburger_v = hamburger_p * hamburger_q
Line 723 ⟶ 831:
Print Using " tax #####################.##";tax/100
Print Using " total #####################.##";subtotal/10+tax/100
Sleep</
Line 729 ⟶ 837:
Frink tracks units of measure through all calculations, so you can specify quantities as "dollar", "cent", etc.
<
st = 4000000000000000 * 5.50 dollars + 2 * 2.86 dollars
tax = round[st * 7.65 percent, cent]
Line 736 ⟶ 844:
println["Tax: " + format[tax, "dollars", 2]]
println["Total: " + format[total, "dollars", 2]]
</syntaxhighlight>
{{out}}
<pre>
Line 742 ⟶ 850:
Tax: 1683000000000000.44 dollars
Total: 23683000000000006.16 dollars
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn Lunch_Invoice( burger_price as CFStringRef, burger_amount as CFStringRef, shake_price as CFStringRef, shake_amount as CFStringRef, tax as CFStringRef )
'~'1
DecimalNumberRef burgerPriceDecimal = fn DecimalNumberWithString( burger_price )
DecimalNumberRef burgerAmountDecimal = fn DecimalNumberWithString( burger_amount )
DecimalNumberRef burgersDecimal = fn DecimalNumberByMultiplyingBy( burgerPriceDecimal, burgerAmountDecimal )
DecimalNumberRef shakePriceDecimal = fn DecimalNumberWithString( shake_price )
DecimalNumberRef shakeAmountDecimal = fn DecimalNumberWithString( shake_amount )
DecimalNumberRef shakesDecimal = fn DecimalNumberByMultiplyingBy( shakePriceDecimal, shakeAmountDecimal )
DecimalNumberRef taxDecimal = fn DecimalNumberWithString( tax )
DecimalNumberRef subtotalDecimal = fn DecimalNumberByAdding( burgersDecimal, shakesDecimal )
DecimalNumberRef taxTotalDecimal = fn DecimalNumberByMultiplyingBy( subtotalDecimal, taxDecimal )
DecimalNumberRef adjTaxTotalDecimal = fn DecimalNumberByAdding( taxTotalDecimal, fn DecimalNumberWithString( @"0.01" ) )
DecimalNumberRef billTotalDecimal = fn DecimalNumberByAdding( subtotalDecimal, adjTaxTotalDecimal )
CFStringRef burgersString = fn DecimalNumberString( burgersDecimal )
CFStringRef shakesString = fn DecimalNumberString( shakesDecimal )
CFStringRef taxTotalString = fn DecimalNumberString( adjTaxTotalDecimal )
CFStringRef billTotalString = fn DecimalNumberString( billTotalDecimal )
printf @"%@", fn StringByPaddingToLength( @"", 55, @"-", 0 )
printf @"Item Price Quantity Cost"
printf @"Hamburgers %6s %18s %18s", fn StringUTF8String( burger_price ), fn StringUTF8String( burger_amount ), fn StringUTF8String( burgersString )
printf @"Milkshakes %6s %18s %18s", fn StringUTF8String( shake_price ), fn StringUTF8String( shake_amount ), fn StringUTF8String( shakesString )
printf @"%@", fn StringByPaddingToLength( @"", 55, @"-", 0 )
printf @"%34s %@", fn StringUTF8String( @"Subtotal:" ), fn DecimalNumberString( subtotalDecimal )
printf @"%35s %@", fn StringUTF8String( @" Tax: " ), fn StringSubstringToIndex( taxTotalString, len(taxTotalString) - 3 )
printf @"%34s %@", fn StringUTF8String( @" Total:" ), fn StringSubstringToIndex( billTotalString, len(billTotalString) - 3 )
end fn
NSLog( @"%@", fn WindowPrintViewString( 1 ) )
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
-------------------------------------------------------
Item Price Quantity Cost
Hamburgers 5.50 4000000000000000 22000000000000000
Milkshakes 2.86 2 5.72
-------------------------------------------------------
Subtotal: 22000000000000005.72
Tax: 1683000000000000.44
Total: 23683000000000006.16
</pre>
=={{header|Go}}==
<
import (
Line 832 ⟶ 988:
fmt.Printf(" Tax: %22s\n", tax)
fmt.Printf(" Total: %22s\n", total)
}</
{{out}}
<pre>
Line 841 ⟶ 997:
=={{header|Haskell}}==
<
import Text.Printf
Line 860 ⟶ 1,016:
printAmount "Subtotal" subtotal
printAmount "Tax" tx
printAmount "Total" total</
{{out}}
Line 874 ⟶ 1,030:
We use a naive implementation with arbitrary precision (rational) numbers:
<
Items=: ;: 'Hamburger Milkshake'
Line 894 ⟶ 1,050:
)
makeBill Items;Prices;Quantities</
{{out}}
<pre> Item Price Quantity Value
Line 907 ⟶ 1,063:
=={{header|Java}}==
<
import java.util.*;
Line 945 ⟶ 1,101:
System.out.printf(" Total: %20.2f%n", subtotal.add(tax));
}
}</
<pre>Subtotal: 22000000000000005.72
Line 952 ⟶ 1,108:
=={{header|JavaScript}}==
<
let hamburgers = 4000000000000000
Line 976 ⟶ 1,132:
console.log('Tax:', taxTotal)
console.log('Total:', total)
</syntaxhighlight>
=={{header|jq}}==
Line 989 ⟶ 1,145:
results as dollars and cents, and when calculating the taxes.
<
# print as dollars and cents
Line 1,032 ⟶ 1,188:
" Total before tax: \($before_tax | dollars($width))",
" - tax: \($taxes | cents | dollars($width))",
" Total after tax: \($after_tax | dollars($width))"</
{{out}}
<pre>
Line 1,043 ⟶ 1,199:
{{works with|Julia|1.2}}
<
p = [big"5.50", big"2.86"]
Line 1,055 ⟶ 1,211:
@printf " - tot. before tax: %20.2f \$\n" beftax
@printf " - tax: %20.2f \$\n" tax
@printf " - tot. after tax: %20.2f \$\n" afttax</
{{out}}
Line 1,063 ⟶ 1,219:
=={{header|Kotlin}}==
<
import java.math.BigDecimal
Line 1,081 ⟶ 1,237:
println("Tax thereon @ 7.65% : ${fmt.format(tax)}")
println("Total price after tax : ${fmt.format(price + tax)}")
}</
{{out}}
Line 1,089 ⟶ 1,245:
Total price after tax : 23683000000000006.16
</pre>
=={{header|Lua}}==
Using the lbc library for arbitrary precision support.
<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
subtot = (C"4000000000000000" * C"5.50" + C"2" * C"2.86"):trunc(2) -- cosmetic trunc
tax = (subtot * C"0.0765" + C"0.005"):trunc(2) -- rounding trunc
total = (subtot + tax):trunc(2) -- cosmetic trunc
print(("Before tax: %20s"):format(subtot:tostring()))
print(("Tax : %20s"):format(tax:tostring()))
print(("With tax : %20s"):format(total:tostring()))</syntaxhighlight>
{{out}}
<pre>Before tax: 22000000000000005.72
Tax : 1683000000000000.44
With tax : 23683000000000006.16</pre>
=={{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].
<syntaxhighlight lang="m2000 interpreter">
Module Currency_Task {
Locale 1033
Line 1,158 ⟶ 1,331:
}
Currency_Task
</syntaxhighlight>
Optional with $ and thousands separator (a smaller version from above)
<syntaxhighlight lang="m2000 interpreter">
Module Currency_Task {
Locale 1033
Line 1,203 ⟶ 1,376:
}
Currency_Task
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,223 ⟶ 1,396:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
Digits := 50;
Line 1,244 ⟶ 1,417:
totalprice := totaltax + total;
printf("%.2f\n",totalprice);
</syntaxhighlight>
{{out}}
<pre>
Line 1,253 ⟶ 1,426:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
AccountingForm[N[total, 20], {\[Infinity], 2}]
tax = total Rationalize[0.0765];
AccountingForm[N[tax, 20], {\[Infinity], 2}]
AccountingForm[N[total + tax, 20], {\[Infinity], 2}]</
{{out}}
<pre>22000000000000005.72
Line 1,268 ⟶ 1,441:
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.
<
import bignum
Line 1,361 ⟶ 1,534:
echo "Total price before tax: ", beforeTaxStr.align(length)
echo "Tax: ", taxStr.align(length)
echo "Total with tax: ", totalStr.align(length)</
{{out}}
Line 1,370 ⟶ 1,543:
=={{header|OCaml}}==
Using the [https://
<syntaxhighlight lang
let () =
let open Decimal in (* bring all functions and operators into scope locally *)
let s = of_string in
let i = of_int in
let
let
let tax_rate = s "7.65e-2" in
let subtotal = hamburgers + milkshakes in
let tax = subtotal * tax_rate in
let total = subtotal + tax in
Printf.printf
"Subtotal: %20s
Tax: %20s
Total: %20s\n"
(to_string (round ~n:2 subtotal))
(to_string (round ~n:2 tax))
(to_string (round ~n:2 total))
</syntaxhighlight>
{{out}}
<pre>
Subtotal: 22000000000000005.72
Tax: 1683000000000000.44
Total: 23683000000000006.16
</pre>
=={{header|Perl}}==
<
@check = (
Line 1,433 ⟶ 1,605:
($q, $r) = dec_rndiv_and_rem("FLR", @_[0], 1);
$q . substr((sprintf "%.2f", $r), 1, 3);
}</
{{out}}
<pre>Item Price Quantity Extension
Line 1,445 ⟶ 1,617:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<
<span style="color: #
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">mpfr_set_default_precision</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ensure accuracy to at least 20 d.p.</span>
Line 1,461 ⟶ 1,632:
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total_price</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tax</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpfr_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total_price</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tax</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 before tax:%
<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:%
<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:%
<!--</
{{out}}
<pre>
Total before tax: 22,000,000,000,000,005.72
Tax: 1,683,000,000,000,000.44
Total: 23,683,000,000,000,006.16
</pre>
=== 64 bit ===
As it happens, 64-bit Phix uses 80-bit floats for atoms, which actually have just enough accuracy for this task:
<!--<syntaxhighlight lang="phix">-->
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #000000;">64</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">total_price</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4000000000000000</span><span style="color: #0000FF;">*</span><span style="color: #000000;">5.5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2.86</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">tax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">total_price</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.0765</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">total_price</span><span style="color: #0000FF;">+</span><span style="color: #000000;">tax</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 before tax:%,26.2f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">total_price</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:%,26.2f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tax</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:%,26.2f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">total</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
with the same output, however (after deleting the first line) under 32-bit (and under p2js) they would incorrectly end in 4.00/0.25/4.00.
=={{header|PicoLisp}}==
<syntaxhighlight lang="text">(scl 2)
(let
(Before
Line 1,484 ⟶ 1,667:
(tab Fmt "Total before tax:" (format Before *Scl "." ","))
(tab Fmt "Tax:" (format Tax *Scl "." ","))
(tab Fmt "Total:" (format Total *Scl "." ",")) )</
{{out}}
<pre>
Line 1,496 ⟶ 1,679:
(and some copying of names from the Raku example).
<
from collections import namedtuple
Line 1,521 ⟶ 1,704:
total = total_before_tax + tax
print(fmt % ('', '', '', '--------------------'))
print(fmt % ('', '', 'Total', total))</
{{out}}
Line 1,532 ⟶ 1,715:
--------------------
Total 23683000000000006.16</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="Quackery"> [ $ "bigrat.qky" loadfile ] now!
[ 100 * n->v ] is dollars ( n --> n/d )
[ n->v v+ ] is cents ( n/d n --> n/d )
[ rot n->v v* ] is cost ( n n/d --> n/d )
[ $->v drop v* 100 n->v v/ ] is tax ( n/d $ --> n/d )
[ 100 n->v v/
2 point$
$ " $" swap join
' [ 2 split nip ] ]do[
dup -3 peek
char . = if done
dup -2 peek
char . = iff
[ char 0 join ]
done
$ ".00" join ] is currency$ ( n/d --> $ )
[ currency$ echo$ ] is echocurrency ( n/d --> )
4000000000000000 5 dollars 50 cents cost
2 2 dollars 86 cents cost v+
say "Total price before tax: " 2dup echocurrency cr
2dup $ "7.65" tax
say "Tax: " 2dup echocurrency cr
v+
say "Total price with tax: " echocurrency cr
</syntaxhighlight>
{{out}}
<pre>Total price before tax: $22000000000000005.72
Tax: $1683000000000000.44
Total price with tax: $23683000000000006.16</pre>
=={{header|Racket}}==
Line 1,540 ⟶ 1,769:
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.
<
(define (cents-* x y)
(/ (round (* 100 x y)) 100))
Line 1,584 ⟶ 1,813:
(for-each show-item all)
(newline)
(show-total all (/ #e7.65 100))</
{{out}}
<pre>hamburger 4000000000000000 $5.50 -> $22000000000000000.00
Line 1,599 ⟶ 1,828:
(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.))
<syntaxhighlight lang="raku"
Hamburger 5.50 4000000000000000
Milkshake 2.86 2
Line 1,626 ⟶ 1,855:
# make up for lack of a Rat fixed-point printf format
sub fix2($x) { ($x + 0.001).subst(/ <?after \.\d\d> .* $ /, '') }</
{{out}}
<pre>Item Price Quantity Extension
Line 1,643 ⟶ 1,872:
Programming note: the tax rate can be expressed with or without a percent ('''%''') suffix.
===without commas===
<
numeric digits 200 /*support for gihugic numbers.*/
taxRate= 7.65 /*number is: nn or nn% */
Line 1,671 ⟶ 1,900:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show$: return right( '$'arg(1), 27) /*right─justify and format a number. */</
{{out|output|text= (attempting to mimic a check-out register to some degree):}}
<pre>
Line 1,687 ⟶ 1,916:
===with commas===
<
numeric digits 200 /*support for gihugic numbers.*/
taxRate= 7.65 /*number is: nn or nn% */
Line 1,719 ⟶ 1,948:
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. */</
{{out|output|text= with commas in the larger numbers:}}
<pre>
Line 1,735 ⟶ 1,964:
=={{header|Ring}}==
<
# Project : Currency
Line 1,748 ⟶ 1,977:
see "tax thereon @ 7.65 : " + tax + nl
see "total price after tax : " + (price + tax) + nl
</syntaxhighlight>
Output:
<pre>
Line 1,755 ⟶ 1,984:
total price after tax : 23683000006.16
</pre>
=={{header|RPL}}==
Need for big integers.
{{works with|RPL|HP-49C}}
« →STR
'''IF''' LASTARG 9 ≤ '''THEN''' "0" SWAP + '''END'''
1 OVER SIZE 2 - SUB
LASTARG NIP 1 + DUP 1 + SUB
"$" ROT SIZE LASTARG "0" IFTE +
"." + SWAP +
» '<span style="color:blue">→CURR</span>' STO
« 100 * R→I *
DUP <span style="color:blue">→CURR</span> CLLCD 1 DISP .5 WAIT
» '<span style="color:blue">→PRICE</span>' STO
« DUPDUP FLOOR - EVAL →NUM
0.5 ≥ SWAP CEIL LASTARG FLOOR IFTE
» '<span style="color:blue">→RND</span>' STO
« 100 * R→I
OVER <span style="color:blue">→CURR</span> "TPBT" →TAG
UNROT OVER * 100000 / <span style="color:blue">→RND</span> DUP <span style="color:blue">→CURR</span> "Tax" →TAG
UNROT + <span style="color:blue">→CURR</span> "TPWT" →TAG
» '<span style="color:blue">TAX→</span>' STO
4000000000000000 5.50 <span style="color:blue">→PRICE</span>
2 2.86 <span style="color:blue">→PRICE</span> +
7.65 <span style="color:blue">TAX→</span>
{{out}}
<pre>
3: TPBT:"$22000000000000005.72"
2: Tax:"$1683000000000000.44"
1: TPWT:"$23683000000000006.16"
</pre>
=={{header|Ruby}}==
<
before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d
Line 1,765 ⟶ 2,029:
Tax: $#{tax.to_s('F')}
Total: $#{total.to_s('F')}"
</syntaxhighlight>
{{out}}
<pre>Before tax: $22000000000000005.72
Line 1,774 ⟶ 2,038:
=={{header|Rust}}==
<
extern crate num_rational; // 0.3.0
Line 1,825 ⟶ 2,089:
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let cents = (&self.amount * BigInt::from(100)).to_integer();
write!(f, "${}.{:0>2}", ¢s / 100, ¢s % 100)
}
}
Line 1,833 ⟶ 2,097:
fn new(num: f64) -> Self {
Self {
amount: BigRational::new(((num * 100.0).round() as i64).into(), 100.into())
}
}
Line 1,844 ⟶ 2,108:
}
}
}</
{{out}}
<pre>
Line 1,855 ⟶ 2,119:
{{libheader|Scala}}Locale is manipulated to demonstrate the behavior with other currencies.
<
import java.util.Locale
Line 1,884 ⟶ 2,148:
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")
}</
{{out}}
4000000000000000 Hamburger XL руб. 5,50 22 000 000 000 000 000,00
Line 1,896 ⟶ 2,160:
=={{header|Sidef}}==
{{trans|Raku}}
<
name, price, quant
}
Line 1,923 ⟶ 2,187:
var total = subtotal+tax
printf(fmt, '', '', 'Total ', total)</
{{out}}
<pre>
Line 1,938 ⟶ 2,202:
Using ScaledDecimal numbers ('sX'-suffix).
{{works with|Smalltalk/X}}
<
" amount name price "
(4000000000000000 'hamburger' 5.50s2 )
Line 1,972 ⟶ 2,236:
Transcript printf:fmt withAll:{'' . '' . 'Total' . (totalSum+totalTax)}.
Transcript cr; printCR:('Enjoy your Meal & Thank You for Dining at Milliways')</
{{out}}
<pre>Item Price Qty Extension
Line 1,987 ⟶ 2,251:
=={{header|Swift}}==
<
extension Decimal {
Line 2,005 ⟶ 2,269:
print("Price before tax: $\(totalBeforeTax)")
print("Total tax to be collected: $\(taxesToBeCollected)")
print("Total with taxes: $\(totalBeforeTax + taxesToBeCollected)")</
{{out}}
Line 2,014 ⟶ 2,278:
=={{header|Tcl}}==
{{tcllib|math::decimal}}<
namespace import math::decimal::*
Line 2,027 ⟶ 2,291:
set total [+ $net $tax]
puts "net=[tostr $net], tax=[tostr $tax], total=[tostr $total]"</
{{out}}
net=22000000000000005.72, tax=1683000000000000.44, total=23683000000000006.16
=={{header|Unicon}}==
Solution takes advantage of Unicon's FxPt class as well as Unicon's operator overloading extension.
<syntaxhighlight lang="unicon">import math
procedure main()
n_burgers := 4000000000000000
n_shakes := 2
price := FxPt(5.50) * n_burgers + FxPt(2.86) * n_shakes
tax := (price * FxPt(7.65/100)).round(2)
total := price + tax
write(left("Price", 10), "$", right(price.toString(),21))
write(left("Tax", 10), "$", right(tax.toString(),21))
write(left("Total", 10), "$", right(total.toString(),21))
end</syntaxhighlight>{{out}}
<pre>Price $ 22000000000000005.72
Tax $ 1683000000000000.44
Total $ 23683000000000006.16</pre>
=={{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.
<
'4000000000000000 hamburgers at $5.50 each
Dim number_of_hamburgers As Variant
Line 2,058 ⟶ 2,342:
'the total with tax
Debug.Print "Total with tax "; Format(total_price_before_tax + tax, "Currency")
End Sub</
<pre>Total price before tax € 22.000.000.000.000.005,72
Tax € 1.683.000.000.000.000,44
Line 2,065 ⟶ 2,349:
=={{header|Wren}}==
{{libheader|Wren-big}}
<
var hamburgers = BigRat.new("4000000000000000")
Line 2,078 ⟶ 2,362:
System.print("Total price before tax : %((totalPreTax).toDecimal(2))")
System.print("Tax : %((totalTax).toDecimal(2))")
System.print("Total price after tax : %((totalAfterTax).toDecimal(2))")</
{{out}}
Line 2,091 ⟶ 2,375:
So, just multiply bucks by 100 and be careful when doing tax calculations.
{{trans|Python}}
<
var taxRate=765; // percent*M
const M=0d10_000;
Line 2,116 ⟶ 2,400:
fmt.fmt("","","","--------------------").println();
fmt.fmt("","","Total",toBucks(totalBeforeTax + tax)).println();
}</
<
{{out}}
<pre>
|