Different numbers become equal after conversion with doubleval [closed]

2

I have 2 values 4850.00 and 4850.01

When I define 2 variables manually with these values and compare using if , it returns me different (OK).

But in an ERP system I develop I get 2 values via AJAX. Both the same values above and even converting to doubleval($var1) doubleval($var2) when using the comparison returns me equal.

    
asked by anonymous 07.08.2015 / 20:01

1 answer

6

And we're going again. I will answer you because you still do not have an answer for PHP, and someone will answer before the question is closed as a duplicate.

You can not use type double or equivalent when you need numerical precision. This type of data is made to process fast and not to be exact.

The ideal in these cases is to use integers and present as you wish, with the amount of houses you want. In other words, treat everything as small as possible, for example, cents, so you do not have to deal with decimals. You'll still have to know how to deal with the necessary rounding.

I doubt that's the case, but if you do not need calculations and just need to compare, treat everything as string . This rarely applies, but it is an option.

Or create or use a class for a decimal or monetary type. You have libraries ready but I do not like them, not even default .

There are several questions on the subject here:

Reading everything, following the link allows you to learn well why this happens and how to avoid in any situation in any language or software.

The problem is this, using the wrong data type will always have problems. Any attempt to get around some gambiarra will only create the illusion of solution.

    
07.08.2015 / 20:14