January 25, 2007

Boolean and 0.00

ARG. I encountered another potential issue in PHP that is due to loose types that is common if you are using a database back end.

$amount = 0.00;
if($amount)

Versus

$amount = ‘0.00′; // how data from databases comes
if($amount)

Guess what happens. Well, most people might say both should be TRUE, but that’s not true!

The first one evaluates like this:

  1. 0.00 is the same as 0
  2. 0 is the same as FALSE.
  3. Evaluate the IF condition as FALSE.

The second one evaluates like this:

  1. “0.00″ is a string.
  2. A non-empty string is the same as TRUE
  3. Evaluate the IF condition as TRUE.

This is a predictable problem, but highly annoying when working with databases. Most people forget that a float field in the database could equal 0.00, but would evaluate as a TRUE when placed in a condition.

As in, when you get results from the database, the NUMBER 0.00 becomes the WORD ”0.00″.

So the lesson here is to make sure you always convert your variables before doing conversions like that. As in:

$amount = ‘0.00′;
if(floatval($amount))

Of course, the best solution is always making comparisons explicit:

$amount = ‘0.00′;
if(0 < floatval($amount))

Filed under: PHP — Michi @ 9:59 pm

Share this

  • Digg
  • Reddit
  • Facebook
  • email
  • StumbleUpon
  • del.icio.us
  • Slashdot
  • DZone
  • Twitter

Related

For those of you who ever have to put data into MySQL database, here's a quick little tip. If you're importing into a table that is using the InnoDb engine (versus the MyISAM), wrap your import file in the following:...
I saw an interesting video today. This post isn't about its political ramifications. In fact, I have no freaking clue what they're trying to say. But the part that caught my eye was this: It's an agenda that -...

No Comments »

TrackBack URI | Blog RSS | Comment RSS

No comments yet.

What do you think?