sprintf formatting of double value sprintf formatting of double value unix unix

sprintf formatting of double value


You get zeros when printing b because you told printf to print 15 decimal places (%.15f), and it is obediently doing so. To get something "exact", you might have better luck with simple %g.


[Update based on recent comments]

Things really depend on what you mean by "exact". If by exact, you mean "what the user originally entered", then a double might not be the best choice for you. Perhaps storing the value as a string and then converting it to a double when you need to use it in a computation might work. Once a text-based decimal number is converted to a double, it generally is no longer exactly the same as the text. While printf() or ostream will dutifully print exactly what the double holds (and sometimes it gets lucky and what it prints looks the same as the original value), the problem is that the double itself no longer holds the actual original value. And in fact it never did.

Alternatively, you might favor a precise numeric implementation rather than something inherently approximate like doubles. For example, MySQL has NUMERIC and DECIMAL types that support perfect precision at the cost of forcing you to specify the number of integer and decimal places ahead of time. This is called arbitrary precision arithmetic and there are libraries for doing this in C/C++.