Convert digits to words PHP script 2 comments


Convert digits to words PHP script



<?php
function convert_number($number) {
    //max eight digit code it will take
    if (($number < 0) || ($number > 999999999)) {
        return "$number";
    }
    $Cn = floor($number / 10000000);  /* Trillaince  */
    $number -= $Cn * 10000000;
    $Gn = floor($number / 100000);  /* Millions (giga) */
    $number -= $Gn * 100000;
    $kn = floor($number / 1000);     /* Thousands (kilo) */
    $number -= $kn * 1000;
    $Hn = floor($number / 100);      /* Hundreds (hecto) */
    $number -= $Hn * 100;
    $Dn = floor($number / 10);       /* Tens (deca) */
    $n = $number % 10;               /* Ones */
    $res = "";
    if ($Cn) {
        $res .= convert_number($Cn) . " Crore ";
    }
    if ($Gn) {
        $res .= ( empty($res) ? "" : " ") .
            convert_number($Gn) . " Lakh";
    }
    if ($kn) {
        $res .= ( empty($res) ? "" : " ") .
                convert_number($kn) . " Thousand";
    }
    if ($Hn) {
        $res .= ( empty($res) ? "" : " ") .
                convert_number($Hn) . " Hundred";
    }
    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",
        "Nineteen");
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
        "Seventy", "Eigthy", "Ninety");
        if ($Dn || $n) {
        if (!empty($res)) {
            $res .= " and ";
        }
        if ($Dn < 2) {
            $res .= $ones[$Dn * 10 + $n];
        } else {
            $res .= $tens[$Dn];

            if ($n) {
                $res .= "-" . $ones[$n];
            }
        }
    }
    if (empty($res)) {
        $res = "zero";
    }
    return $res;
}

$number = '98765786';
echo "<br />" . $number . "<br />";
echo convert_number($number);
?>

output

98765786
Nine Crore Eigthy-Seven Lakh Sixty-Five Thousand Seven Hundred and Eigthy-Six

Share on Facebook




About Pragnesh Karia

Pragnesh Karia, Open Source Enthusiast, Software Professional, Software Developer, Technical Lead ,Magento, Joomla ,Joomla LMS , Moodel LMS ,PHP ,Mysql, Ajax, Javascript, Jquery, Linux, Fan of Open Sources , Annet Technologies , SEO Analyst , Mootools


2 thoughts on “Convert digits to words PHP script