Kind of "financial" integer printing format

Is there some way with a Printf format string to say this:

  Printf.sprintf "%03d_%03d_%03d" millions thousands units

But, without having to compute millions, thousands and units (as I naively implemented)?

I.e. I would like to have a ‘_’ to separate every three digits starting from the right.

1 Like

Yes, it is documented in the manual: Printf.sprintf "%#d".

Cheers,
Nicolas

9 Likes

Indeed: OCaml library : Printf

d, i: convert an integer argument to signed decimal. The flag # adds underscores to large values for readability.

I never spotted it in the manual; probably because there is not the keywork “financial”.

1 Like

I didn’t know this ! It’s a pity it doesn’t work for floats.

1 Like

Same, it’s cool. However floats also have their own hidden gem, for
those who don’t know: exact printing in hexadecimal!

# Printf.printf "%h\n" 42.1;;
0x1.50ccccccccccdp+5

If only this was supported in more languages…

6 Likes

This was already specified in C99 with the format specifier %a, some 15 years before OCaml’s implementation…

Cheers,
Nicolas

2 Likes

See also:

Having something like that in OCaml would be indeed useful.

We do have something like this in OCaml :slight_smile:

2 Likes

I wonder if fixed point arithmetic would go significantly faster than regular floats.
I wonder if this would be useful for scientific calculations (like Molecular Dynamics).
Cc @scemama

A very good reference for throughput and latencies of CPU instructions is this document:

Based on this data, I would say that in the general case (64 bits) it would be slower:

  • Integer division usually takes more cycles than float division
  • There is no equivalent of fused multiply-add with integers
  • It will require a conversion to float call high-performance libraries like BLAS
  • In OCaml, there is a special treatment for float arrays to improve performance.

For memory-bound algorithms, if a fixed-point format with a reduced number of bits can be used without loss of precision, it could be beneficial by increasing the memory throughput.

2 Likes