3

Here is a very simple code.

$a = 2000000.00000000;
$b = 0.00000001;

echo $a-$b; //output 2000000

I was expecting 1999999.99999999. 

Can someone explain how to make it work ? It would be very appreciate.

Darren
  • 13,050
  • 4
  • 41
  • 79

1 Answers1

4

You can set the precision used when formatting floats as strings using the precision ini setting, the default being 14:

ini_set('precision', 16);
echo $a - $b; // 1999999.99999999

Also, read this article for a more generic breakdown on the subject.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • just curious - what's the default? –  Jul 11 '14 at 01:57
  • @Dagon I think the default is 14. – Ja͢ck Jul 11 '14 at 01:58
  • 1
    @Dagon It is 14 as Jack stated, [**`This`**](http://www.leaseweblabs.com/2013/06/the-php-floating-point-precision-is-wrong-by-default/) is an interesting read related to it aswell! – Darren Jul 11 '14 at 01:59
  • 1
    your right, found it on 2nd attempt. my google foo is weak today –  Jul 11 '14 at 02:00
  • Wow. Thank you very much for your help. I have set ini precision to 24 (i am storing in mysql in decimal(24,8). Now if i try i get (1999999.99999998998828232) as output. Using round($result, 8) don't work. Is there a way to limit it to 8 decimals ? – BlackCrypto Jul 11 '14 at 02:07
  • @BlackCrypto You can use `round()` to mitigate that. – Ja͢ck Jul 11 '14 at 02:07
  • what sort of cazy math you doing needing that precision? –  Jul 11 '14 at 02:08
  • @Dagon With PHP, the math *must* be crazy by definition :) – Ja͢ck Jul 11 '14 at 02:08
  • 1
    who knew `crazy string` was actully the model of the universe. any excuse for xkcd reference: http://xkcd.com/171/ –  Jul 11 '14 at 02:09
  • @Jack Too easy :) Share the knowledge! Better than being a grungy old man haha! – Darren Jul 11 '14 at 02:11