Domanda

Can somebody explain this ?

echo ceil( 20.7 * 100 ); // returns 2070
echo ceil( 2070 );       // returns 2070

all OK and logical, but

echo ceil( 40.7 * 100 ); // returns 4071
echo ceil( 4070 );       // returns 4070

not OK and not logical...

Why is this difference ?

Thanks

È stato utile?

Soluzione

Floating point numbers issue... you can overcome your problem with something like this:

echo ceil( (int) (40.7 * 100) );

Altri suggerimenti

The wonderful world of floating point numbers:

printf("%.18f\n", 40.7*100);

//prints 4070.000000000000454747

printf("%.18f\n", 20.7*100);

//prints 2070.000000000000000000

In short: floating point numbers cannot represent all rational numbers exactly. In particular, neither 407/10 nor 207/10 can be represented exactly, and so the result of integer conversion always has an uncertainty of one unit.

The only rational numbers which can be represented exactly as binary floating point numbers are of the form "small odd integer times power of two", or in other words, those which have a small binary expansion.

Floating point errors. 40.7 cannot be represented exactly in a float. It'll be something like 40.700000001 or whatever. When you * 100 and ceil it, it rounds up to 4071.

Use arbitrary precision library bcmath e.g.:

ceil(bcmul(40.7, 100)); // 4070
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top