Re: converting float to double



2006-12-21 <1166716794.786619.301600@xxxxxxxxxxxxxxxxxxxxxxxxxxx>,
Dilip wrote:
William Hughes wrote:
Ernie Wright wrote:
CBFalconer wrote:

Ernie Wright wrote:
CBFalconer wrote:
Ben Pfaff wrote:

For what it's worth, the round function is new in C99.

and unnecessary.

price_cents = 100 * floating_price + 0.5;

which is only one of several widely used rounding rules, and not
necessarily the one preferred for financial transactions.

which won't matter in the case posted by the OP. He started with a
constant of the form 89.13, i.e. with exactly 2 decimal places.

I infer that he started with a 32-bit IEEE float, which can only have
exactly two decimal places if they happen to be ".25", ".50" or ".75".

No, the "two decimal places" refers to the desired value,
a value known by the supplier of the stock prices.
What he has is a float that approximates the desired value.
As you note, this will rarely be exact.

This is **exactly** true.

Once again I cannot convince my boss to remove that nasty
mutiply/divide by 1000.0 kludge since he seems to believe that solves
whatever problem they have been having. Please read my very first post
to understand why I say this -- this kludge rounded off the number to
the nearest cent higher than the floating point representation and he
seems to be happy with that. (i.e what started off with
59.889999389648437 caused problems and what made him happy after the
kludge was the fact the same number got approximated as
59.890000000000001).

Everyone posted here seems incredibly astute -- I am almost cowering in
comparison. But the good thing I found the right way to solve this
problem. Here is what I have come up with: (i am not suggesting to the
management as yet though).

int main()
{
float f = 59.89F;
double d = ff;

double d_fractional, d_integral, d_floorvalue;
d_fractional = d_integral = d_floorvalue = 0;
d_fractional = modf(d, &d_integral);
d_floorvalue = floor(d_fractional*100.0 + 0.5) / 100.0;

double result = d_integral + d_floorvalue;

return 0;
}

Am I in the right direction?

Actually, I'd say eschew floating point except where necessary

#include <math.h>
int main() {
float f=59.89f;
long cents;
#if __STDC_VERSION__ >= 199901L
cents = lrint(f*100.0)
#else
/* This code does not handle negative numbers correctly, but it's
not needed for your case. */
cents = (f*100.0+0.5)
#endif

printf("%d.%02d",cents/100,cents%100);

/*Use integral cents [or thousandths, or whatever precision you're
supposed to be using, I don't think you've told us] for all further
calculations.*/
}

This is financial data, you can't afford to be screwing around with
floating point more than is _strictly_ necessary.

Get it into your boss's head that the problem is caused by the use of
floating point, and multiplying/dividing by 0x1.f4p+9 is not going to
solve anything in the long run.
.