1

I would like to truncate numbers at 3 decimals with php :

3.236665   3.236
3.236111   3.236

Thanks

mlwacosmos
  • 4,391
  • 16
  • 66
  • 114

1 Answers1

3

To truncate a number up to p decimals, multiply the number by p-th power of 10, truncate the fraction by casting to integer, then divide the result by p-th power of 10.

The following truncates $n up to the 3rd decimal:

intval($n * 1e3) / 1e3;
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
  • 2
    I would like to say this solution is mostly accurate but there exceptions where the result is wrong. Example : if $n = 1.005, int ($n * 1e3) = 1004 and not 1005 due to float approximation – mlwacosmos Nov 15 '16 at 15:36