tags:

views:

91

answers:

4

Hello

I have this code for a school assignment, but i can't manage to format it. When i run the program i keep getting 1.27768e-307.

lp->price is a double with the value of 1000000.0000000000

printf("Price of flat: %g\n", lp->price); 

Any ideas? The other double values gets formatted correctly, just not price.

+8  A: 

Please note that floating-point data types are really ill-suited for representing money.

Then try:

printf("Price: %6f\n", lp->price);

The %f specifier does not use scientific notation.

unwind
+1 for highlighting the inappropriate data type. Using an int/long to represent (for example) number of cents would eliminate many arithmetic problems, but would make it trickier to handle rounding errors (adding sales tax for example) and trickier to output the result (convert to string and insert the decimal point in the right place).
Skizz
Why are floating point types, such as double precision, ill-suited for representing money? Many modern computers have built-in floating point processing and can often process floating point numbers either as as fast as integers or faster. The conversion between floating point to integral may waste any value gained by the integral operations.
Thomas Matthews
@Thomas: Because they are *floating point*. Once you have enough dollars, you no longer have any cents. People who count money don't like to count like that. Also, they're unable to exactly represent some values, even though there would seem to be precision enough.
unwind
We had to use it, was stated in the instructions for the assignment.
Patrick
A: 

%g will print your double in either normal or exponential format. %f is for when you always want it in decimal notation.

See also http://en.wikipedia.org/wiki/Printf#printf_format_placeholders and http://man.cx/printf%283%29

-- {edit: I deleted this answer as another one was already given, but I realize mentioning what %g does would be useful}

phresnel
A: 

Make sure your lp->price is really a double, not a pointer to something (double*) or array of something (double[]).

KennyTM
+2  A: 

(1) Since you are using a double, you should add the l length specifier:

That's not true. The l length specifier is not used in %e, %f or %g; these conversions take a double anyway. (Use the L length specifier to take a long double.)

Because printf is a varargs function, if you give it a float, it automatically promotes it to double.

tpr
Don't post comments as answers.
unwind
@tpr and @unwind +1, both since tpr is new and his contribution adds value.
Hassan Syed