1

Sample Input

-33.8670522

151.1977362

12.9582505

Required Output

-33.86

151.19

12.95

Output that i am getting

-33.87

151.20

12.96

Below is my code but issue is it is rounding off the last digit

$n_va = substr($va, 0, $va < 0 ? 3 : 2);

Can anybody help me with it!!!!

Teemu
  • 22,918
  • 7
  • 53
  • 106
Shreyas Heda
  • 111
  • 8
  • 1
    I would check out https://www.php.net/manual/en/function.round.php – Ebski Apr 17 '20 at 12:04
  • Also check out https://www.php.net/manual/en/function.number-format.php – aynber Apr 17 '20 at 12:08
  • 2
    Does this answer your question? [PHP dropping decimals without rounding up](https://stackoverflow.com/questions/9079158/php-dropping-decimals-without-rounding-up) – iainn Apr 17 '20 at 12:13

1 Answers1

2

To get your desired results, multiply the numbers by 100, take the intval to truncate to the integer part and then divide by 100 again:

$values = array(-33.8670522, 151.1977362, 12.9582505);

foreach ($values as $value) {
    echo intval($value * 100) / 100 . PHP_EOL;
}

Output:

-33.86
151.19
12.95

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95