Mostafa Talebi - 8 months ago 26

PHP Question

I get a number from database and this number might be either

`float`

`int`

I need to set the decimal precision of the number to

`3`

`5.020`

`1518845.756`

Using PHP

`round( $number ,$decision )`

I see a problem:

It rounds the number. I need a function to only cut the decimals short, without changing their values which

`round( )`

Answer

You can use `number_format()`

to achieve this:

```
echo number_format((float) $number, $precision, '.', '');
```

This would convert `1518845.756789`

to `1518845.757`

.

But if you just want to cut off the number of decimal places short to 3, and ** not round**, then you can do the following:

```
$number = intval($number * ($p = pow(10, $precision))) / $p;
```

It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 10^{3} (it becomes `1518845756.789`

), cast it to an integer so everything after the 3 decimal places is removed (becomes `1518845756`

), and then divide the result by 10^{3} (becomes `1518845.756`

).