Removing useless decimal of number_format with PHP

Published on 2022-04-04 • Modified on 2022-04-04

In this snippet, we see how to remove useless decimal of number_format with PHP. This trick is only helpful if you want to have localized decimal and thousand separators. If you don't need this, a string cast on the float variable does the job, as shown in the second foreach loop.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet196Trait
{
    public function snippet196(): void
    {
        $floats = [
            10,
            10.00,
            10.01,
            10.10,
            10.99,
            10.01010,
            11111.001001000,
        ];

        var_dump($floats);
        echo PHP_EOL;

        foreach ($floats as $idx => $float) {
            echo 'nĀ°'.$idx.': '.number_format($float, 2).' -> '.$this->numberFormatRemoveExtra($float).PHP_EOL;
        }

        echo PHP_EOL.'-- With string cast '.PHP_EOL;

        foreach ($floats as $idx => $float) {
            echo 'nĀ°'.$idx.': '.$float.PHP_EOL; // cast is automatic (if possbile) when concatening two variables
        }

        // That's it! šŸ˜
    }

    private function numberFormatRemoveExtra(float $number): string
    {
        $float = explode('.', (string) $number);
        $right = $float[1] ?? '';

        return number_format($number, \strlen($right), ',', '.');
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!