0

In PHP, I am getting numbers from a database with 3 decimal places. I want to remove the last decimal point. So 2.112 will become 2.11, 23.123 will become 23.12 and 123.267 will become 123.26. Its like doing a floor at a decimal level.

Justin
  • 23
  • 1
  • 6
  • Using number_format or round a number like 534.386 will become 534.39. I want it to become 534.38 – Justin Dec 15 '15 at 23:20

2 Answers2

1

You can use number_format, you specify the number of decimal places as the second arugment.

Example

$number = 534.333;

echo number_format($number,2) // outputs 534.33

Or use round

$number = 549.333;
echo round($number, 2) // outputs 534.33

Seems like substr is what solved the question in the end

substr($number,0,-1); // everything besides the last decimal
Antonio Smoljan
  • 2,187
  • 1
  • 12
  • 11
0
<?php

    $a = floor($a*100)/100;

So you can do something like that:

<?php

    // Note might overflow so need some checks
    function round_floor($number, $decimals) {
      $n = pow(10, $decimals);
      return floor($number * $decimals)/$decimals;
    }

    echo round_floor(2.344, 2); // Would output 2.34
    echo round_floor(2.344, 1); // Would output 2.3

Another option if numbers are large:

<?php
    // $decimal should be positive
    function round_floor($number, $decimals) {
        $a = strstr($number, '.', true);
        $b = strstr($number, '.');
        return $a . substr($b, 0, $decimal -1);
    }
E_p
  • 3,136
  • 16
  • 28