Currency: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
(Use decimal library)
Line 1,422: Line 1,422:
=={{header|OCaml}}==
=={{header|OCaml}}==


Using the [https://github.com/janestreet/bignum Bignum] library.
Using the [https://ocaml.org/p/decimal/0.3.0 decimal] library.


<syntaxhighlight lang="ocaml">#require "bignum" ;;
<syntaxhighlight lang="ocaml">
let () =
let open Decimal in (* bring all functions and operators into scope locally *)
let s = of_string in
let i = of_int in


let p1 = Bignum.((of_string "4000000000000000") * (of_float_decimal 5.50)) ;;
let hamburgers = s "4e15" * s "5.50" in
let p2 = Bignum.((of_int 2) * (of_float_decimal 2.86)) ;;
let milkshakes = i 2 * s "2.86" in
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
let r1 = Bignum.(p1 + p2) ;;
"Subtotal: %20s
let r2 = Bignum.(r1 * (of_float_decimal (7.65 /. 100.))) ;;
Tax: %20s
let r3 = Bignum.(r1 + r2) ;;
Total: %20s\n"

(to_string (round ~n:2 subtotal))
let my_to_string v =
(to_string (round ~n:2 tax))
Bignum.(v |> round_decimal ~dir:`Nearest ~digits:2
(to_string (round ~n:2 total))
|> to_string_hum ~decimals:2) ;;
</syntaxhighlight>

let () =
Printf.printf "before tax: %s\n" (my_to_string r1);
Printf.printf "tax: %s\n" (my_to_string r2);
Printf.printf "total: %s\n" (my_to_string r3);
;;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Subtotal: 22000000000000005.72
$ opam install bignum
Tax: 1683000000000000.44
$ opam install utop
Total: 23683000000000006.16
$ eval $(opam env)
$ utop currency.ml
before tax: 22000000000000005.72
tax: 1683000000000000.44
total: 23683000000000006.16
</pre>
</pre>