-3

I'm trying to round up the value if it has cents, for example:

69990 to be 70000, I'm working on none USD currency, I've tried many answers in the community, I couldn't make it work .

My example code :

$gg = rtrim(number_format(69990, 1), '.');
echo $gg . "\n <br />";
echo round($gg , 2, PHP_ROUND_HALF_UP);
echo  "\n <br />";
echo number_format($gg,2);

And the output is :

69,990.0
 <br />69
 <br />69.00
0stone0
  • 34,288
  • 4
  • 39
  • 64
Kodr.F
  • 13,932
  • 13
  • 46
  • 91
  • you need to read the docs carefully – Noman Nov 09 '20 at 13:18
  • 4
    `round` expects a float value as first parameter, you are giving it a string. So that string value needs to be casted into a float first - but you provided it in a format, that PHP does not “understand”. PHP does not recognize the comma as thousands-separator, this is an _invalid_ character in a number to PHP, so it cuts of before that. Therefor the actual value you are “rounding” _is_ only 69 at that point already. – CBroe Nov 09 '20 at 13:20
  • @CBroe also when i do ` floatval(number_format(69990,` its give 69 – Kodr.F Nov 09 '20 at 13:22

1 Answers1

1

PHP's round():

Rounds a float


You're trying to 'round' on each 1000'st number.

You should use php's ceil() like so;

<?php

    $n = 69990;
    
    // WRONG: Only for decimals
    echo round($n , 2, PHP_ROUND_HALF_UP) . PHP_EOL;
    // 69990
    
    // Nearest 'whole'
    echo ceil($n / 1000) * 1000 . PHP_EOL;
    // 70000

Try online

How to round up a number to nearest 10?

0stone0
  • 34,288
  • 4
  • 39
  • 64