add amount.mli

This commit is contained in:
swrup 2025-11-20 22:14:45 +01:00
parent 58bce4efa2
commit 9b760b436f
5 changed files with 48 additions and 17 deletions

View file

@ -1,7 +1,7 @@
(* TODO
have safe amount arithmetic
make type private
use config currency option *)
redefine an Amount module with currency enforced to be Config.currency? *)
(* Amounts of currency, serialized as `<Currency>:<IntegerPart>.<FractionalPart>`
Fixed-precision numbers with 8 decimal places.
- <Currency> must be at most 11 characters long
@ -11,9 +11,13 @@
Prefixed with '+' or '-' in certain contexts.
When no sign is present, the amount is assumed to be positive. *)
type sign =
| Sign_plus
| Sign_minus
type t = {
sign: [ `Plus | `Minus ] option;
currency: [ `Eur ];
sign: sign option;
currency: string;
value: Int64.t;
fraction: Int32.t;
}
@ -37,11 +41,12 @@ let make ~sign ~currency ~value ~fraction =
let pp =
let open Fmt in
let pp_sign ppf = function `Plus -> char ppf '+' | `Minus -> char ppf '-' in
let pp_currency ppf = function `Eur -> string ppf "EUR" in
let pp_sign ppf = function
| Sign_plus -> char ppf '+'
| Sign_minus -> char ppf '-'
in
fun ppf { sign; currency; value; fraction } ->
pf ppf "%a%a:%Ld.%02ld" (Fmt.option pp_sign) sign pp_currency currency value
fraction
pf ppf "%a%s:%Ld.%02ld" (Fmt.option pp_sign) sign currency value fraction
let to_string = Fmt.str "%a" pp
@ -50,11 +55,16 @@ let of_string =
let parse_sign =
choice
[
char '+' *> return (Some `Plus); char '-' *> return (Some `Minus);
return None;
char '+' *> return (Some Sign_plus);
char '-' *> return (Some Sign_minus); return None;
]
in
let parse_currency = string "EUR" *> return `Eur in
let parse_currency =
(* TODO currency string constraint/format *)
take_while1 (function
| 'a' .. 'z' | 'A' .. 'Z' -> true
| _ -> false)
in
let parse_int64 =
take_while1 (function '0' .. '9' -> true | _ -> false)
>>| Int64.of_string_opt