Search code examples
formattingocaml

Modifiers on %a specifier?


After consulting the Format and Printf module documentation, I'm still left with an unanswered question about the %a specifier.

Starting with a very simple type:

type b = C of float

I can easily create a printing routine:

let pp ppf (C f) = 
  Format.fprintf ppf "%.2f" f

Such that Format.asprintf "%a" pp (C 7.6) yields "7.60".

Now, Format.asprintf "%.3a" pp (C 7.6) runs without issue, but of course I still get "7.60".

Is there a way to access the modifier within pp to determine the precision to use?


Solution

  • The %a specifier does not accept any flag, padding or width arguments. Historically, the interpretation of the specifier was lax and silently ignored any such arguments

    Format.printf "%0.3a"
    

    However, enabling -strict-formats make the compiler reject this erroneous format string with

    Error: invalid format "%0.3a": at character number 0, `padding' is incompatible with 'a' in sub-format "%0.3a"