Search code examples
phpnumber-formatting

I am struggling with PHP number formatting


I am extremely new to PHP, and I am having some issues with the number_format() function.

I am performing a calculation which is, correctly, returning this result: 6215. However, I want this value to be displayed/echoed as 62.15. I have played around with the number_format() function to no avail.

Any help would be greatly appreciated!


Solution

  • You have 2 potential tasks here.

    1.) You want to change your number (divide by 100)

    <?php
      $number = 6215;
      $number = $number / 100;
      echo $number;
    ?>
    Renders as 62.15
    

    2.) You may want additional formatting to make a "pretty" number

    From the docs: https://www.php.net/manual/en/function.number-format.php

    // Function signature syntax
    number_format(
        float $num,
        int $decimals = 0,
        ?string $decimal_separator = ".",
        ?string $thousands_separator = ","
    )
    
    <?php
      $number = 1006215.56;
      $pretty_number = number_format($number, 2, '.', '');
      echo $pretty_number;
    ?>
    Renders as 1,006,215.56