How to Format numbers to nearest thousands in php

Avatar
C

Callum Davies

Senior Backend Engineer••
7614Views
5mRead
0Reactions

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.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?What's your production setup for this scenario? Have you encountered similar architectural bottlenecks or edge-case gotchas?

Recommended Resources & Courses

Partner Links
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article