Simple Operation get wrong result


#1

info:
PHP Version 5.1.6

Why do i get this value in a simple operation?

<?php echo (1.2 - 0.1) - 1.1; ?>

result = -2.2204460492503E-016


#2

Sounds like it’s the same as in Java: you’re working with floats, which arn’t ‘exact’. I presume they’re an approximation of the value you’d like stored, and for a certain amount of decimals, they’re exact, but not if you want it more precise. I believe by default PHP does 15 decimals exact. But displaying a value that ‘approximates’ 0 would have that effect I guess, especially with the scientific notation. intval() would work to solve this problem:

[php]

<?php echo intval((1.2 - 0.1) - 1.1); ?>

[/php]


#3

yes its a solution but i need to have precision on this function and when this happens it blows.

:-?

#4

If you want precision, floats arn’t the way to go. If you know how many decimals you want, you could use integers and multiply them by 10^x (where x is the amount of decimals). That way, no precision will be lost and you’ll be working with exact numbers. To display the integer, you could divide by 10^x to make it a decimal number and echo :slight_smile:

As a cheap alternative, there’s round().