How to convert amount in crores to decimal value in php?
<?php
function count_digit($number) {
return strlen($number);
}
function divider($number_of_digits) {
$tens="1";
if($number_of_digits>8)
return 10000000;
while(($number_of_digits-1)>0)
{
$tens.="0";
$number_of_digits--;
}
return $tens;
}
//function call
$num = "789";
$ext="";//thousand,lac, crore
$number_of_digits = count_digit($num); //this is call :)
if($number_of_digits>3)
{
if($number_of_digits%2!=0)
$divider=divider($number_of_digits-1);
else
$divider=divider($number_of_digits);
}
else
$divider=1;
$fraction=$num/$divider;
$fraction=number_format($fraction,2);
if($number_of_digits==4 ||$number_of_digits==5)
$ext="k";
if($number_of_digits==6 ||$number_of_digits==7)
$ext="Lac";
if($number_of_digits==8 ||$number_of_digits==9)
$ext="Cr";
echo $fraction." ".$ext;
?>
- count the number_of_digit
- Take (number_of_digit-1) digit tens value
- divide it.
- find the extension of value from number of digits.
- output will be
123456789 = 12.34 Cr
23456789 = 2.34 Cr
3456789 = 34.56 Lac
456789 = 4.56 Lac
56789 = 56.78 K
6789 = 6.78 K
If any testcase fails . Please let me know. I will rectify
You Can also try my code, May be it will help you:
function no_to_words($no)
{
if($no == 0) {
return ' ';
}else {
$n = strlen($no); // 7
switch ($n) {
case 3:
$val = $no/100;
$val = round($val, 2);
$finalval = $val ." hundred";
break;
case 4:
$val = $no/1000;
$val = round($val, 2);
$finalval = $val ." thousand";
break;
case 5:
$val = $no/1000;
$val = round($val, 2);
$finalval = $val ." thousand";
break;
case 6:
$val = $no/100000;
$val = round($val, 2);
$finalval = $val ." lakh";
break;
case 7:
$val = $no/100000;
$val = round($val, 2);
$finalval = $val ." lakh";
break;
case 8:
$val = $no/10000000;
$val = round($val, 2);
$finalval = $val ." crore";
break;
case 9:
$val = $no/10000000;
$val = round($val, 2);
$finalval = $val ." crore";
break;
default:
echo "";
}
return $finalval;
}
}
echo no_to_words(12345676);
You can modify function based on your requirement.