I have to reimplement printf(3)
with C
without using any function that would do the conversion for me.
I'm nearly done I just need %a
and it's also nearly done thanks to you guys : How %a conversion work in printf statement?
The man says:
The double argument is rounded and converted to hexadecimal notation in the style[-]0xh.hhhp[+-]d, where the number of digits after the hexadecimal-point character is equal to the precision specification.
So my question is rounded how ?
I found: printf rounding behavior for doubles
And it explains that printf is using banker round or Round half to even but I have no idea how to implement it I have tried this:
a_double = round(a_double * pow(10, precision)) / pow(10, precision)
But on 1000000
tests starting from 0.000001
and adding 0.000001
each time it fails 405201
times, for example with 0.000011
:
printf("%.6a", 0.000011) => 0x1.711948p-17
myprintf("%.6a", 0.000011) => 0x1.711947p-17
The rounding 'failed' and I didn't get the same value as the real printf.
I don't think that the algorithm that transforms the double
to hexa notation
is wrong because with a precision of 13
I have absolutely no errors.
So I just would like to know how I could do the same rounding that printf
does on the double
.