Karthik
Karthik

Reputation: 5757

Number to Words Conversion (Indian Rupee) decimal String issue in php

I using Following function to convert numbers to word Conversion in PHP.

I Expected Result.

one thousand five hundred and forty two Rupees twenty six Paise Only

but, its Display

one thousand five hundred and forty two Rupees two six Paise Only

My Function is :

function displaywords($number){
   $no = round($number);
   $point = round($number - $no, 2) * 100;
   $hundred = null;
   $digits_1 = strlen($no);
   $i = 0;
   $str = array();
   $words = array('0' => '', '1' => 'one', '2' => 'two',
    '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
    '7' => 'seven', '8' => 'eight', '9' => 'nine',
    '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
    '13' => 'thirteen', '14' => 'fourteen',
    '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
    '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
    '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
    '60' => 'sixty', '70' => 'seventy',
    '80' => 'eighty', '90' => 'ninety');
   $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
   while ($i < $digits_1) {
     $divider = ($i == 2) ? 10 : 100;
     $number = floor($no % $divider);
     $no = floor($no / $divider);
     $i += ($divider == 10) ? 1 : 2;


     if ($number) {
        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
        $str [] = ($number < 21) ? $words[$number] .
            " " . $digits[$counter] . $plural . " " . $hundred
            :
            $words[floor($number / 10) * 10]
            . " " . $words[$number % 10] . " "
            . $digits[$counter] . $plural . " " . $hundred;
     } else $str[] = null;
  }
  $str = array_reverse($str);
  $result = implode('', $str);


  $points = ($point) ?
    "" . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : ''; 

  if($points != ''){        
  echo $result . "Rupees  " . $points . " Paise Only";
} else {

    echo $result . "Rupees Only";
}

}

$ins=1542.26;

echo displaywords($ins);

Upvotes: 2

Views: 6763

Answers (3)

Sanath L S
Sanath L S

Reputation: 1468

<?php
set_error_handler('exceptions_error_handler');

function exceptions_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}

function convert_number_to_words($number) {

$hyphen      = '-';
$conjunction = ' and ';
$separator   = ', ';
$negative    = 'negative ';
$decimal     = ' point ';
$dictionary  = array(
    0                   => 'zero',
    1                   => 'one',
    2                   => 'two',
    3                   => 'three',
    4                   => 'four',
    5                   => 'five',
    6                   => 'six',
    7                   => 'seven',
    8                   => 'eight',
    9                   => 'nine',
    10                  => 'ten',
    11                  => 'eleven',
    12                  => 'twelve',
    13                  => 'thirteen',
    14                  => 'fourteen',
    15                  => 'fifteen',
    16                  => 'sixteen',
    17                  => 'seventeen',
    18                  => 'eighteen',
    19                  => 'nineteen',
    20                  => 'twenty',
    30                  => 'thirty',
    40                  => 'fourty',
    50                  => 'fifty',
    60                  => 'sixty',
    70                  => 'seventy',
    80                  => 'eighty',
    90                  => 'ninety',
    100                 => 'hundred',
    1000                => 'thousand',
    100000             => 'lakh',
    10000000          => 'crore'
);

if (!is_numeric($number)) {
    return false;
}

if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
    // overflow
    trigger_error(
        'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
        E_USER_WARNING
    );
    return false;
}

if ($number < 0) {
    return $negative . convert_number_to_words(abs($number));
}

$string = $fraction = null;

if (strpos($number, '.') !== false) {
    list($number, $fraction) = explode('.', $number);
}

switch (true) {
    case $number < 21:
        $string = $dictionary[$number];
        break;
    case $number < 100:
        $tens   = ((int) ($number / 10)) * 10;
        $units  = $number % 10;
        $string = $dictionary[$tens];
        if ($units) {
            $string .= $hyphen . $dictionary[$units];
        }
        break;
    case $number < 1000:
        $hundreds  = $number / 100;
        $remainder = $number % 100;
        $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
        if ($remainder) {
            $string .= $conjunction . convert_number_to_words($remainder);
        }
        break;
    case $number < 100000:
        $thousands   = ((int) ($number / 1000));
        $remainder = $number % 1000;

        $thousands = convert_number_to_words($thousands);

        $string .= $thousands . ' ' . $dictionary[1000];
        if ($remainder) {
            $string .= $separator . convert_number_to_words($remainder);
        }
        break;
    case $number < 10000000:
        $lakhs   = ((int) ($number / 100000));
        $remainder = $number % 100000;

        $lakhs = convert_number_to_words($lakhs);

        $string = $lakhs . ' ' . $dictionary[100000];
        if ($remainder) {
            $string .= $separator . convert_number_to_words($remainder);
        }
        break;
    case $number < 1000000000:
        $crores   = ((int) ($number / 10000000));
        $remainder = $number % 10000000;

        $crores = convert_number_to_words($crores);

        $string = $crores . ' ' . $dictionary[10000000];
        if ($remainder) {
            $string .= $separator . convert_number_to_words($remainder);
        }
        break;
    default:
        $baseUnit = pow(1000, floor(log($number, 1000)));
        $numBaseUnits = (int) ($number / $baseUnit);
        $remainder = $number % $baseUnit;
        try
        {
        $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
        }catch(Exception $e)
        {
            return "Value too large";
        }
        if ($remainder) {
            $string .= $remainder < 100 ? $conjunction : $separator;
            $string .= convert_number_to_words($remainder);
        }
        break;
}

if (null !== $fraction && is_numeric($fraction)) {
    $string .= $decimal;
    $words = array();
    foreach (str_split((string) $fraction) as $number) {
        $words[] = $dictionary[$number];
    }
    $string .= implode(' ', $words);
}

return $string;
}

echo convert_number_to_words(100000000);
?>

Upvotes: 1

Andreas
Andreas

Reputation: 23968

I reworked the code slightly to a more efficient code. (I think).
It uses less variables, no imploding, no array functions, less ifs, and less calculations.

It explodes the number at . and makes it an array and handles them seperatly in the same code ($val).
Then it takes each number of the string and str_pads it to it's "main number" (don't know a better way of saying it).
So 1526, it looks at the 1, and makes it 1000 with str_pad.
If it's above 90 use both $words and $digits.

This code will also handle numbers like 0.50, or 10.

function displaywords($number){
    $words = array('0' => '', '1' => 'one', '2' => 'two',
    '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
    '7' => 'seven', '8' => 'eight', '9' => 'nine',
    '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
    '13' => 'thirteen', '14' => 'fourteen',
    '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
    '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
    '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
    '60' => 'sixty', '70' => 'seventy',
    '80' => 'eighty', '90' => 'ninety');
    $digits = array('', '', 'hundred', 'thousand', 'lakh', 'crore');

    $number = explode(".", $number);
    $result = array("","");
    $j =0;
    foreach($number as $val){
        // loop each part of number, right and left of dot
        for($i=0;$i<strlen($val);$i++){
            // look at each part of the number separately  [1] [5] [4] [2]  and  [5] [8]

            $numberpart = str_pad($val[$i], strlen($val)-$i, "0", STR_PAD_RIGHT); // make 1 => 1000, 5 => 500, 4 => 40 etc.
            if($numberpart <= 20){ // if it's below 20 the number should be one word
                $numberpart = 1*substr($val, $i,2); // use two digits as the word
                $i++; // increment i since we used two digits
                $result[$j] .= $words[$numberpart] ." ";
            }else{
                //echo $numberpart . "<br>\n"; //debug
                if($numberpart > 90){  // more than 90 and it needs a $digit.
                    $result[$j] .= $words[$val[$i]] . " " . $digits[strlen($numberpart)-1] . " "; 
                }else if($numberpart != 0){ // don't print zero
                    $result[$j] .= $words[str_pad($val[$i], strlen($val)-$i, "0", STR_PAD_RIGHT)] ." ";
                }
            }
        }
        $j++;
    }
    if(trim($result[0]) != "") echo $result[0] . "Rupees ";
    if($result[1] != "") echo $result[1] . "Paise";
    echo " Only";
}

$ins=1516.16;

echo displaywords($ins);

https://3v4l.org/rFvbJ

added some comments to the code.
Noticed it was giving wrong outputs on larger numbers, corrected.

Upvotes: 1

mokamoto12
mokamoto12

Reputation: 383

function displaywords($number){
   $no = (int)floor($number);
   $point = (int)round(($number - $no) * 100);
   $hundred = null;
   $digits_1 = strlen($no);
   $i = 0;
   $str = array();
   $words = array('0' => '', '1' => 'one', '2' => 'two',
    '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
    '7' => 'seven', '8' => 'eight', '9' => 'nine',
    '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
    '13' => 'thirteen', '14' => 'fourteen',
    '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
    '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
    '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
    '60' => 'sixty', '70' => 'seventy',
    '80' => 'eighty', '90' => 'ninety');
   $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
   while ($i < $digits_1) {
     $divider = ($i == 2) ? 10 : 100;
     $number = floor($no % $divider);
     $no = floor($no / $divider);
     $i += ($divider == 10) ? 1 : 2;


     if ($number) {
        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
        $str [] = ($number < 21) ? $words[$number] .
            " " . $digits[$counter] . $plural . " " . $hundred
            :
            $words[floor($number / 10) * 10]
            . " " . $words[$number % 10] . " "
            . $digits[$counter] . $plural . " " . $hundred;
     } else $str[] = null;
  }
  $str = array_reverse($str);
  $result = implode('', $str);


  if ($point > 20) {
    $points = ($point) ?
      "" . $words[floor($point / 10) * 10] . " " . 
          $words[$point = $point % 10] : ''; 
  } else {
      $points = $words[$point];
  }
  if($points != ''){        
      echo $result . "Rupees  " . $points . " Paise Only";
  } else {

      echo $result . "Rupees Only";
  }

}


echo displaywords(1542.26);
echo "\n";
echo displaywords(1542.58);

Upvotes: 3

Related Questions