3

Let's say I have:

echo 1/3;

And it print out only 0.33333333333333, can I get more digits?

Templar
  • 1,843
  • 7
  • 29
  • 42

4 Answers4

6

Can use bcdiv

echo bcdiv(1, 3, 20);

The third argument

is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Paul
  • 6,572
  • 2
  • 39
  • 51
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • There's no floating point when I use bcdiv? Like in Stefan's answer? – Templar Jun 27 '11 at 11:25
  • 2
    @Templar the [numbers are represented as strings](http://de3.php.net/manual/en/intro.bc.php), so you can have precision until you run out of memory :) – Gordon Jun 27 '11 at 11:34
3

Edit the precision configuration variable either in your php.ini or some other configuration location or use ini_set().

ini_set('precision', 22);
echo 1/3;
// 0.3333333333333333148296

Even though I highly doubt that you really need that kind of precision ;-)

EDIT

As Gordon said: you'll hit the floating point precision limit in PHP sooner or later (depending on the precision specified). So the better way would be to use either the BCMath Arbitrary Precision Mathematics extension or the GNU Multiple Precision extension, if you're after real high precision mathematics.

Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
2

You might want tto look into the BC arbitary precision php library http://php.net/manual/en/book.bc.php

jcoder
  • 29,554
  • 19
  • 87
  • 130
1

The setting is precision: http://es.php.net/manual/en/ini.core.php

However, I would not use it except for debugging purposes. Have a look at number_format()

Álvaro González
  • 142,137
  • 41
  • 261
  • 360