The random eclecticisms of loonytoons

PHP Rounding Issue

So today I came across a wierd rounding issue in PHP, where the round function was just not returning the result that I was expecting. It seemed to be rounding the value down rather than up.

Passing a float value of 14.875 (generated by a multiplier calculation) I was expecting the result 14.88 but was actually recieving 14.87. Reading around I know that there are a few issues and difficulties when it comes to dealing with float numbers, precision and rounding, though later versions of php may well handle these slightly better (on this project I’m using php 5.2.6, running on Ubuntu 4.6).

The easiest way that I found to get around the problem was to turn the number that I sent into round into a string, simply by concatenating an empty string on the end, eg round($value.”). I think that this then makes the value a simple string of 14.875 that can be easily rounded rather than a float that is susceptible to the nuances of precision rounding, though I’m really not an expert and simply speculating here.

This also may not be the best or most elegant way to sort this problem but it worked for me.

If you know of a better way to get around this then do please let me know, I’d be really interested to hear how other people have got around this issue.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *