# Replacement for snprintf

berni44 dlang at d-ecke.de
Wed Oct 30 19:11:14 UTC 2019

```On Wednesday, 30 October 2019 at 17:41:26 UTC, H. S. Teoh wrote:
>
> 	https://www.zverovich.net/2019/02/11/formatting-floating-point-numbers.html
>
> especially the papers linked in the first paragraph.

Thanks for that link. I havn't had a look into the grisu
algorithms. But I'll definitivly do that.

> Formatting floating-point numbers is not a trivial task. It's
> easy to write up something that works for common cases, but
> it's not so easy to get something to gives the best results in
> *all* cases.

I know, that this is something we all wish. Anyway, my goal is
set somewhat lower: I'd like to replace the existing call to
snprintf with something that is programmed in D and which should
be pure, @safe and ctfeable. And ideally it should not be slower
then snprintf.

> You probably should use the algorithms referenced above for

I read through the paper for the ryu algorithm and rejected it
(at least for me; if someone else is goint to implement it and
file a PR that's fine). My reason for rejecting is, that the
algorithm has not exactly the same goal as printf, which IMHO
means, that it cannot be used here; and that it needs a
lookuptable, that is too large (300K for 128bit reals).

I fear a little bit, from what I read in the ryu paper about the
grisu algorithms, that it has the first of the above mentioned
problems too. But yet I can't tell for sure.

> unexpected corner cases that don't produce the right output.

Obviously I need to prove, that the algorithm is correct somehow.
While this can be done for floats by running it on all numbers
and comparing these results with the result of snprintf (or the
result calculated by bc), for doubles and reals, this isn't
possible anymore (a random sample can be tested anyway, but
that's no proof). Anyway, I think, that the proof isn't hard to
give. The current algorithm is short and straight forward. (And:
When I implement one of the mentioned algorithms, it can still
contain bugs, because I made a mistake somewhere.)
```