PHP Type Casting

In PHP, because variables aren’t given definitive data types PHP will do conversions on the fly. This can lead to some unusual quirks. Recently I was using the round() function to round the decimals after a number. For some reason the function returned a whole number without the decimals. After a bit of digging around, it turned out I was passing an object into round() and so PHP must have been converting it to an integer before rounding. My quick fix was to type cast the variable like so:

$roundedValue = round( (float)$value, 2 );

Advertisements

Published by:

Skyrail

Production Facilitator at Audacious Church Previously Software Developer at UKFast Ltd. and Web Applications Developer at SenseLogix Ltd. Graduate of Renewable Energy BSc from the University of Exeter. Experience with PHP, MySQL, Javascript, CSS and HTML.

Categories PHP, ProgrammingLeave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s