Chris
Chris

Reputation: 36496

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?

Upvotes: -1

Views: 47

Answers (2)

octachron
octachron

Reputation: 18902

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"

Upvotes: 3

glennsl
glennsl

Reputation: 29106

The direct answer to your question, as @octachron's already covered, is essentially "no". But you can still alter the precision of your pp function by adding a precision argument to it and using the .* precision specifier instead:

let pp precision ppf (C f) = 
  Format.fprintf ppf "%.*f" precision f
Format.asprintf "%a" (pp 2) (C 7.6);; (* prints 7.60 *)
Format.asprintf "%a" (pp 3) (C 7.6);; (* prints 7.600 *)

Upvotes: 1

Related Questions