How to convert numbers to words in php?

By Shubham G on Apr 18, 2024 632 Views

Learn how to convert numbers into words in PHP. Our comprehensive guide provides step-by-step instructions on using the NumberFormatter class, part of PHP's Internationalization Functions (Intl), to transform numerical values into their English word equivalents. Ideal for developers looking to enhance the readability of their applications.

In PHP, you can convert numbers to words using the NumberFormatter class, which is part of the Internationalization Functions (Intl). Here's a simple function that does this:

function numberToWords($number)
{
    $formatter = new NumberFormatter("en", NumberFormatter::SPELLOUT);
    $words = $formatter->format($number);
    return $words;
}

You can use this function like so:

echo numberToWords(12345);  
// Outputs: "twelve thousand three hundred forty-five"

This function works by creating a new NumberFormatter object with the 'en' locale and the SPELLOUT style. The format method is then called on this object to convert the number to words.


Please note that this function requires the Intl extension to be installed and enabled in your PHP environment. If it's not already enabled, you can usually enable it by uncommenting or adding the line extension=intl in your php.ini file and restarting your web server.

Categories : PHP

Tags: #PHP

  • Related Posts
Loading...