NYCPHP Meetup

NYPHP.org

[nycphp-talk] Rounding floats

Chris Snyder chsnyder at gmail.com
Tue Sep 14 15:57:55 EDT 2010


I inherited an application that seems to take extreme measures to
eliminate floating point errors when dealing with currency values.

I'm seeing things like:

// add amounts to get total
$total = 0;
foreach( $records AS $rec ) {
  $total = round( round( $total, 2 ) + round( $rec['amt'], 2 ), 2 );
}

This is making my eyes bleed, but if I change it then I have to test
like crazy to make sure some subtle bug hasn't crept in.

I know that float rounding errors can cause problems with comparison,
but in addition and subtraction?

Is it safe to get rid of this round( round() + round() ) pattern?

Chris Snyder
http://chxor.chxo.com/



More information about the talk mailing list