Currency: Difference between revisions

Use decimal library
m (syntax highlighting fixup automation)
(Use decimal library)
Line 1,422:
=={{header|OCaml}}==
 
Using the [https://githubocaml.comorg/janestreetp/bignumdecimal/0.3.0 Bignumdecimal] library.
 
<syntaxhighlight lang="ocaml">#require "bignum" ;;
let () =
let open Decimal in (* bring all functions and operators into scope locally *)
let s = of_string in
let i = of_int in
 
let p1hamburgers = Bignum.((of_strings "40000000000000004e15") * (of_float_decimals "5.50))" ;;in
let p2milkshakes = Bignum.((of_inti 2) * (of_float_decimals "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}}
<pre>
before taxSubtotal: 22000000000000005.72
$ opam install bignum
tax: Tax: 1683000000000000.44
$ opam install utop
total: Total: 23683000000000006.16
$ eval $(opam env)
$ utop currency.ml
before tax: 22000000000000005.72
tax: 1683000000000000.44
total: 23683000000000006.16
</pre>