Currency: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
(Use decimal library) |
||
Line 1,422: | Line 1,422: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Using the [https:// |
Using the [https://ocaml.org/p/decimal/0.3.0 decimal] library. |
||
<syntaxhighlight lang="ocaml"> |
<syntaxhighlight lang="ocaml"> |
||
⚫ | |||
let open Decimal in (* bring all functions and operators into scope locally *) |
|||
let s = of_string in |
|||
let i = of_int in |
|||
let |
let hamburgers = s "4e15" * s "5.50" in |
||
let |
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) ;; |
|||
⚫ | |||
⚫ | |||
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); |
|||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
⚫ | |||
$ opam install bignum |
|||
⚫ | |||
$ opam install utop |
|||
⚫ | |||
$ eval $(opam env) |
|||
$ utop currency.ml |
|||
⚫ | |||
⚫ | |||
⚫ | |||
</pre> |
</pre> |
||