Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf formatting of double value

Tags:

c++

c

unix

printf

I have one specific problem while converting double values to string using sprintf() in UNIX.

For example I have two values:

double a = 0.009984354523452;
double b = 0.01;

While converting, I am using:

sprintf(somestringvar, "Double value : %.15f \n", a);
sprintf(diffstringvar, "Double value : %.15f \n", b);

to convert to a string.

My problem is for the 'a', the value is printing properly but for the value of 'b', 0's are appended at the tail end. Please provide me any common way to represent 'a' and 'b' as exact values.

like image 381
sandy Avatar asked Apr 26 '12 06:04

sandy


1 Answers

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++.

like image 138
Randall Cook Avatar answered Sep 30 '22 18:09

Randall Cook