Different numbers become equal after conversion with doubleval

Asked

Viewed 488 times

4

I have 2 values 4850.00 and 4850.01

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

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

  • 1

    Can you put the code and check the size of the strings as well? in this example with a space between the decimal separator he just considered the numerical value and discarded the rest.

  • 1

    I cannot reproduce the problem. See: http://ideone.com/GQ2SkS

  • I’m sorry but I was wrong. In the comparison I used a variable with very similar name and so the error occurred. Sorry for my lack of attention. (It could only be that msm rsrs).

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

7

And we’ll go again. I’ll answer because I don’t have an answer for PHP yet, and someone will answer before the question is closed as duplicate.

You can’t use like double or equivalent when numerical accuracy is required. 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 number of houses you want. In other words, treat everything as the smallest unit possible, for example, pennies, so you don’t have to take care of the decimals. You still have to know how to handle the necessary rounding.

I doubt that’s the case, but if you don’t need calculations and all you have to do is compare, just treat it like string. This rarely applies, but is an option.

Or create or use a class for a decimal or monetary type. You have libraries ready but I don’t like them, not even the pattern.

There are several questions on the subject here:

See also What is the correct way to use the float, double and decimal types?.

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

The problem is, using the wrong kind of data will always get you into trouble. Any attempt to circumvent with some gambit will only create the illusion of solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.