Laravel 10 Convert Number To Words Example Tutorial

Reading Time: 9 minutes
414 Views

Converting numbers to words is a useful function in many web applications, including e-commerce platforms, invoicing systems, and any other situation where you need to display sums in a more human-readable way.

Laravel, a robust PHP framework, can quickly aid this conversion. We will walk you through the process of converting numbers to words in Laravel 10, allowing you to present numerical data in a more user-friendly and intelligible manner.

Number To Words,

120: One Hundred Twenty

4500: Four Thousand and Five Hundreds

Read More: Laravel 10 Add Custom Search Filter To YajraBox Datatable

By the end of this course, you’ll have the skills and knowledge to improve your Laravel 10 applications by converting numbers to words, allowing users to perceive numerical data in a more intuitive and user-friendly manner.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Method #1: Convert Number To Words (Helper Method)

Open project into terminal and create a controller,

php artisan make:controller NumberController

It will create a controller file NumberController.php inside /app/Http/Controllers folder.

Open file and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NumberController extends Controller
{
    public function index()
    {
        $word = $this->numberToWord(120);
        print($word);

        echo "<br>";

        $word = $this->numberToWord(4500);
        print($word);

        echo "<br>";

        $word = $this->numberToWord(58010);
        print($word);
    }
  
    public function numberToWord($num = '')
    {
        $num    = (string) ((int) $num);

        if ((int) ($num) && ctype_digit($num)) {
            $words  = array();

            $num    = str_replace(array(',', ' '), '', trim($num));

            $list1  = array(
                '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
            );

            $list2  = array(
                '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
                'seventy', 'eighty', 'ninety', 'hundred'
            );

            $list3  = array(
                '', 'thousand', 'million', 'billion', 'trillion',
                'quadrillion', 'quintillion', 'sextillion', 'septillion',
                'octillion', 'nonillion', 'decillion', 'undecillion',
                'duodecillion', 'tredecillion', 'quattuordecillion',
                'quindecillion', 'sexdecillion', 'septendecillion',
                'octodecillion', 'novemdecillion', 'vigintillion'
            );

            $num_length = strlen($num);
            $levels = (int) (($num_length + 2) / 3);
            $max_length = $levels * 3;
            $num    = substr('00' . $num, -$max_length);
            $num_levels = str_split($num, 3);

            foreach ($num_levels as $num_part) {
                $levels--;
                $hundreds   = (int) ($num_part / 100);
                $hundreds   = ($hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ($hundreds == 1 ? '' : 's') . ' ' : '');
                $tens       = (int) ($num_part % 100);
                $singles    = '';

                if ($tens < 20) {
                    $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
                } else {
                    $tens = (int) ($tens / 10);
                    $tens = ' ' . $list2[$tens] . ' ';
                    $singles = (int) ($num_part % 10);
                    $singles = ' ' . $list1[$singles] . ' ';
                }
                $words[] = $hundreds . $tens . $singles . (($levels && (int) ($num_part)) ? ' ' . $list3[$levels] . ' ' : '');
            }
            $commas = count($words);
            if ($commas > 1) {
                $commas = $commas - 1;
            }

            $words  = implode(', ', $words);

            $words  = trim(str_replace(' ,', ',', ucwords($words)), ', ');
            if ($commas) {
                $words  = str_replace(',', ' and', $words);
            }

            return $words;
        } else if (!((int) $num)) {
            return 'Zero';
        }
        return '';
    }
}

Here, you can see we have defined a helper method within controller class with name numberToWord. The complete logic to convert numeric value to words by this helper method.

Add Route

Open web.php file from /routes folder and add this route into it,

//...

use App\Http\Controllers\NumberController;

Route::get('number-to-words', [NumberController::class, "index"]);

//...

Once we will call the route, output will be:

One Hundred Twenty
Four Thousand and Five Hundreds
Fifty Eight Thousand and Ten

Next,

Method #2: Number To Words (Custom Blade Directive)

You’ll Create a custom laravel directive here i.e @numberToWord()

Let’s register first this custom directive. Open AppServiceProvider.php file from /app/Providers folder.

Read More: How To Integrate Google Translator with Laravel 10 Tutorial

Update this provider with this following updated code,

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Blade::directive('numberToWord', function ($num) {

            $num  = (string) ((int) $num);

            if ((int) ($num) && ctype_digit($num)) {
                
                $words  = array();

                $num    = str_replace(array(',', ' '), '', trim($num));

                $list1  = array(
                    '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                    'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                    'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
                );

                $list2  = array(
                    '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
                    'seventy', 'eighty', 'ninety', 'hundred'
                );

                $list3  = array(
                    '', 'thousand', 'million', 'billion', 'trillion',
                    'quadrillion', 'quintillion', 'sextillion', 'septillion',
                    'octillion', 'nonillion', 'decillion', 'undecillion',
                    'duodecillion', 'tredecillion', 'quattuordecillion',
                    'quindecillion', 'sexdecillion', 'septendecillion',
                    'octodecillion', 'novemdecillion', 'vigintillion'
                );

                $num_length = strlen($num);
                $levels = (int) (($num_length + 2) / 3);
                $max_length = $levels * 3;
                $num    = substr('00' . $num, -$max_length);
                $num_levels = str_split($num, 3);

                foreach ($num_levels as $num_part) {
                    $levels--;
                    $hundreds   = (int) ($num_part / 100);
                    $hundreds   = ($hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ($hundreds == 1 ? '' : 's') . ' ' : '');
                    $tens       = (int) ($num_part % 100);
                    $singles    = '';

                    if ($tens < 20) {
                        $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
                    } else {
                        $tens = (int) ($tens / 10);
                        $tens = ' ' . $list2[$tens] . ' ';
                        $singles = (int) ($num_part % 10);
                        $singles = ' ' . $list1[$singles] . ' ';
                    }
                    $words[] = $hundreds . $tens . $singles . (($levels && (int) ($num_part)) ? ' ' . $list3[$levels] . ' ' : '');
                }
                $commas = count($words);
                if ($commas > 1) {
                    $commas = $commas - 1;
                }

                $words  = implode(', ', $words);

                $words  = trim(str_replace(' ,', ',', ucwords($words)), ', ');
                if ($commas) {
                    $words  = str_replace(',', ' and', $words);
                }
            } else if (!((int) $num)) {
                $words = 'Zero';
            } else {
                $words = '';
            }

            return $words;
        });
    }
}

Usage of Custom Directive

You can use @numberToWord() directive inside blade templates.

In your blade template file, you need to use like this:

//...

@numberToWord(1256)

//...

Output,

One Thousand and Two Hundreds Fifty Six

That’s it.

We hope this article helped you to learn about Laravel 10 Convert Number To Words Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.