0

I have a problem with some SQL value & PHP. I am doing 2 request, one to add a value into my sql and the other one to minus this result.

Here it is :

$totaux = $montant_actuel + ($nbre_dej * $prix_dejeuner) + ($nbre_din * $prix_diner) + ($nbre_soir_etape * $prix_etape);

When i'm doing this, it's equal to:

sum = 0 + (15.8*1) + (15.8*1) + (57.8*0)

So I have : 31.6

But when i'm trying to do :

$totaux = $montant_actuel - ($nbre_dej * $prix_dejeuner) - ($nbre_din * $prix_diner) - ($nbre_soir_etape * $prix_etape);

sum = 31.6 - (15.8*1) - (15.8*1) - (57.8*0)

And then, when i insert it into my DB i have this record : 0.0000000000000142109 instead of 0

I don't understand why is this happening.

Perry
  • 11,172
  • 2
  • 27
  • 37
  • 1
    You should read [What Every Programmer Should Know About Floating Point Arithmetic](http://floating-point-gui.de/) –  Jun 24 '13 at 10:10
  • http://stackoverflow.com/questions/3726721/php-math-precision/3726761#3726761 – Mark Baker Jun 24 '13 at 10:12

2 Answers2

1

it seems like a simple rounding error inside the database. if you're using float or double change it to decimal to avoid rounding errors.

Andreas Linden
  • 12,489
  • 7
  • 51
  • 67
  • Decimal is displaying all 0 value after "," and rounding ? it's perfect for my use. Thanks you – user2515736 Jun 24 '13 at 10:17
  • decimal does not round, but you can specify the number of decimal places. if needed you can round manually in php before writing into the database. – Andreas Linden Jun 24 '13 at 10:18
0

It can be a problem with precision of numbers... use some functions from: here

Cracker0dks
  • 2,422
  • 1
  • 24
  • 39