How to Format numbers to nearest thousands in php

1 min read

In this article, you can learn how to display numbers in Kilo, Millions, Billions, or Trillion Format. Sometimes, we need to format numbers into a currency format. It will help you to generate a custom currency format. Let's see a code example:

// Defining function
function numberFormatToCurrency($number) {

    if( $number > 1000 ) {
        $number_round = round($number);
        $number_format = number_format($number_round);
        $num_array = explode(',', $number_format);
        $format_parts = array('k', 'm', 'b', 't');
        $count_parts = count($num_array) - 1;
        $num_display = $number_round;
        $num_display = $num_array[0] . ((int) $num_array[1][0] !== 0 ? '.' . $num_array[1][0] : '');
        $num_display .= $format_parts[$count_parts - 1];
        return $num_display;
    }

    return $number;
}
// Function calling
echo  numberFormatToCurrency(3000);

Output:

3k

I hope it will help you to format numbers into currency.

Related Post

How to increase maximum execution time in PHP
How to generate random Hex color in PHP
How to get the php.ini file path in PHP?
How to Solve PHP Fatal error: Allowed memory size of 8388608 bytes exhausted
Maksud

Maksud

I am a thinker, not a talker.