Express Amount In Words with Decimal Value - php
Im using the number formatter class in php and it needs to format it in currency and also in words, the problem is the value that it needs to be formatted has decimal value and it gives me the value two thousand nine hundred three point zero four and it shoud be two thousand nine hundred three and four cents, if the value has decimal it gives me a literal word point here is my code
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
$formated = $f->format(2903.04);
please help me thanks
There's no defined spell-out formatter for currency, and while you could probably write one I think that that might be a bit of overkill.
What you could do instead is split the dollars as cents into separate values, spell those out, and combine them.
First and foremost though, you do not want to store or compute currencies with floating point representations. I was going to save this point for last, but I couldn't even get through the initial steps before floating point errors crept in.
$v = 2903.04;
$d = (int)$v; // casting to int discards decimal portion
$c = (int)(($v - $d) * 100);
var_dump($v, $d, ($v - $d) * 100, $c);
Output:
float(2903.04)
int(2903)
float(3.9999999999964)
int(3)
Use something like moneyphp/money which stores monetary values as integer amounts of base currency units. [eg: $2903.04 == 290304] This avoids errors like the above, as well as messy kludges to do with rounding. Additionally, money libraries will implement safe mathematical operations to do operations like dividing $1.00 among 3 recipients without splitting or losing pennies.
Instead, let's write the code like:
$a = 290304; // full amount in cents
$c = $a % 100; // cent remainder
$d = ($a - $c) / 100; // dollars
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
var_dump(
$a, $d, $c,
sprintf("%s dollars and %s cents", $f->format($d), $f->format($c))
);
Output:
int(290304)
int(2903)
int(4)
string(54) "two thousand nine hundred three dollars and four cents"
Check my working converter : https://smctgroup.com/contracts/number.php
Input: 2903.04
Output : Two Thousand Nine Hundred Three Pesos and Four Centavos
You can change Pesos to Dollar
You can use this function:
function makewords($numval)
{
$moneystr = "";
$num_arr = explode(".", $numval);
$decnum = $num_arr[1];
// handle the millions
$milval = (integer)($numval / 1000000);
if($milval > 0)
{
$moneystr = getwords($milval) . " Million";
}
// handle the thousands
$workval = $numval - ($milval * 1000000); // get rid of millions
$thouval = (integer)($workval / 1000);
if($thouval > 0)
{
$workword = getwords($thouval);
if ($moneystr == "")
{
$moneystr = $workword . " Thousand";
}
else
{
$moneystr .= " " . $workword . " Thousand";
}
}
// handle all the rest of the dollars
$workval = $workval - ($thouval * 1000); // get rid of thousands
$tensval = (integer)($workval);
if ($moneystr == "")
{
if ($tensval > 0)
{
$moneystr = getwords($tensval);
}
else
{
$moneystr = "Zero";
}
}
else // non zero values in hundreds and up
{
$workword = getwords($tensval);
$moneystr .= " " . $workword;
}
// plural or singular 'dollar'
$workval = (integer)($numval);
if ($workval == 1)
{
$moneystr .= " Peso";
}
else
{
$moneystr .= " Pesos";
}
// //My cents
// if ($workint > 0) {
// $moneystr .= " and ";
// if ($workint < 20) {
// $moneystr .= $ones[$workint];
// } elseif ($workint < 100) {
// $moneystr .= $tens[substr($workint, 0, 1)];
// $moneystr .= " ".$ones[substr($workint, 1, 1)];
// }
// }
// do the pennies - use printf so that we get the
// same rounding as printf
$workstr = sprintf("%3.2f",$numval); // convert to a string
$intstr = substr($workstr,strlen - 2, 2);
$workint = (integer)($intstr);
if($decnum>0) {
$moneystr .= " and ";
if ($workint == 0)
{
$moneystr .= "Zero";
}
else
{
$moneystr .= getwords($decnum);
}
if ($workint == 1)
{
$moneystr .= " Centavo";
}
else
{
$moneystr .= " Centavos";
}
}
// done - let's get out of here!
return $moneystr;
}
Related
If a number is too large use an abbreviation
I am creating a social site. And I want to show people things like their total amount of likes, followers and people they are following. The way it is now, it shows the total amount of likes, followers and following as a whole number and if it's too long it will go over other words on the page. So how do I use abbreviations like: K(for thousands), m(millions) etc ? This is what I have now. $stmt = $con->prepare('SELECT name, username, num_likes, profile_pic FROM users WHERE user_closed = "0" ORDER BY num_likes DESC LIMIT 100'); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($name, $username, $num_likes, $profile_pic); function convert($num_likes) { $num_likes = $number / 1000; return $num_likes . 'k'; } This is how I show the result: <p> Total Likes: " . $num_likes ."</p> I tried the following: PHP Count round thousand to a K style count like facebook Share . . . Twitter Button ect Shorten long numbers to K/M/B? PHP Count round thousand to a K style count Facebook Share
First of all, your function: function convert($num_likes) { $num_likes = $number / 1000; return $num_likes . 'k'; } will not work as expected, because it converts to the opposite way :) Here is updated version: function convert($num_likes) { $number = $num_likes / 1000; return $number . 'k'; } Second point. You should use the function somewhere... for example your line (actually only a part of it): <p> Total Likes: " . $num_likes ."</p> must be: <p> Total Likes: " . convert($num_likes) ."</p> And finally, using this answer we can modify convert function to this: function convert($n) { if ($n < 1000) { $n_format = number_format($n); } else if ($n < 1000000) { // Anything less than a million $n_format = number_format($n / 1000, 3) . 'k'; } else if ($n < 1000000000) { // Anything less than a billion $n_format = number_format($n / 1000000, 3) . 'M'; } else { // At least a billion $n_format = number_format($n / 1000000000, 3) . 'B'; } return $n_format; } Now we can convert all numbers up to billions. Playground: click.
Perhaps like this, Use round() if you don't want large fractions. <?php function convert(int $number) { if ($number >= 1E9) { return round($number / 1E9, 2).'b'; } else if ($number >= 1E6) { return round($number / 1E6, 2).'m'; } else if ($number >= 1E3) { return round($number / 1E3, 2).'k'; } return $number; } echo convert(1000000000).PHP_EOL; // 1b echo convert(1000000).PHP_EOL; // 1m echo convert(1200).PHP_EOL; // 1.2k echo convert(1234).PHP_EOL; // 1.23k echo convert(100).PHP_EOL; // 100 https://3v4l.org/cc54H
Japanese currency formatting for readability
I'd like to format Japanese currency into the standard "quickly readable" format. Basically, all amounts over 10,000 yen are written using the character "万" (pronounced "man"). More on "万" http://www.romajidesu.com/kanji/%E4%B8%87 So, 1,000,000 yen would simply be 100万 or "one hundred man". That's roughly $1,000 USD. Virtually no one in Japan would ever say "one million yen". The currency is always broken into 10,000 yen bundles. Consequently, when you buy a car, the sticker on the windshield says (e.g.) "140万" So, I'd like to display that format. However, number_format, I believe, does not allow for defining the separation at 10,000, and money_format is likewise unhelpful. Any thoughts on a best practice method for accomplishing this? In summary: 10,000 yen should read 1万 100,000 yen should read 10万 1,000,000 yen should read 100万
I have ever written that in my WordPress plugin, /** * convert number expressions to value * * #assert ("34000") == "3万4000円" * #assert ("123456.789") == "12万3457円" * #assert ("1234567890") == "12億3456万7890円" * #assert ("92610000000000") == "92兆6100億円" */ public static function formatInJapanese($value) { $isApproximate = false; $formatted = ''; if ($value > 1000000000000) { if ($value % 1000000000000 !== 0) { $isApproximate = true; } $unitValue = floor($value / 1000000000000); $formatted .= $unitValue . '兆'; $value -= $unitValue * 1000000000000; } if ($value > 100000000) { if ($value % 100000000 !== 0 && !$isApproximate) { $isApproximate = true; } $unitValue = floor($value / 100000000); $formatted .= $unitValue . '億'; $value -= $unitValue * 100000000; } if ($value > 10000) { if ($value % 10000 !== 0 && !$isApproximate) { $isApproximate = true; } $unitValue = floor($value / 10000); $formatted .= $unitValue . '万'; $value -= $unitValue * 10000; } if ($value != 0) { $formatted .= round($value); } return $formatted . '円'; } It only works with man, oku and cho. Quick search gives me that Ruby gem number_to_yen doing similar.
The solution I came up with is similar to the above. function format_yen_for_display($yenAmount) { /* Converts Japanese currency to easily readable local format 10,000 yen should read 1万 100,000 yen should read 10万 1,000,000 yen should read 100万 1,259,000 yen should read 125万 9,000円 */ if($yenAmount > 10000) { //amount over 1万 $manYen = floor($yenAmount/10000); //amount under 1万 $remainderYen = ($yenAmount - ($manYen * 10000)); //concat $returnNum = "<span class=\"ylarge\">" . $manYen . "万</span>"; //if remainder is more than zero, show it if($remainderYen > 0) { //format remainder with thousands separator $remainderYen = number_format($remainderYen); $returnNum .= "<span class=\"ysmall\">" . $remainderYen ."円</span>"; } } else { $returnNum = "<span class=\"ylarge\">" . $yenAmount . "円</span>"; } return $returnNum; }
PHP slightly increment value based on number of decimals
I am trying to slightly increment a value based on the number of decimals it has. For example if the value is 1.2 I would increase it by 0.1, 12.345 by 0.001, 12.345678 by 0.000001, etc. I currently have a long implementation using a chain of if, else if. I know this is not the most efficient way and a loop can be used, but I was unsure of how to structure the loop. I tried using the PHP substr_replace function, but I could not get it to work for this. Is there another way I can structure a loop to reduce my lines of code and be more efficient? Here is my php code so far: $valueOne = 12.345678; // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; /* this also works for finding how many decimals $test = floatval($valueOne); for ( $decimal_count = 0; $test != round($test, $decimal_count); $decimal_count++ ); echo $decimal_count; */ // see value before change echo $valueOne; if ($decimal == "1") { $valueOne = $valueOne + 0.1; } else if ($decimal == "2") { $valueOne = $valueOne + 0.01; } else if ($decimal == "3") { $valueOne = $valueOne + 0.001; } // etc ... // see value after change echo $valueOne; /* i tried messing around with using a loop, but did not have much luck $start = 0.1; $count = 0; $position = 2; while ($count != $decimal) { echo substr_replace($start, 0, $position, 0) . "<br />\n"; $count++; //$position++; } */
Get the number of digits after the decimal. Then create a number with a decimal point, one less 0, followed by 1, to get the amount to add. $valueOne = 12.345678; // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; // see value before change echo $valueOne . "<br>\n"; // Get amount to add $increment = '.' . str_repeat('0', $decimal-1) . '1'; $valueOne += $increment; echo $valueOne;
Get the number of decimals Multiply by the appropriate factor so the number is now an integer Increment by 1 Divide by the same factor to get back to the original number (properly incremented) function increment($number){ // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; $factor = pow(10,$decimal); $incremented = (($factor * $number) + 1) / $factor; return $incremented; }
How to display Currency in Indian Numbering Format in PHP?
I have a question about formatting the Rupee currency (Indian Rupee - INR). For example, numbers here are represented as: 1 10 100 1,000 10,000 1,00,000 10,00,000 1,00,00,000 10,00,00,000 Refer Indian Numbering System I have to do with it PHP. I have saw this question Displaying Currency in Indian Numbering Format. But couldn't able to get it for PHP my problem. Update: How to use money_format() in indian currency format?
You have so many options but money_format can do the trick for you. Example: $amount = '100000'; setlocale(LC_MONETARY, 'en_IN'); $amount = money_format('%!i', $amount); echo $amount; Output: 1,00,000.00 Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows. Pure PHP Implementation - Works on any system: $amount = '10000034000'; $amount = moneyFormatIndia( $amount ); echo $amount; function moneyFormatIndia($num) { $explrestunits = "" ; if(strlen($num)>3) { $lastthree = substr($num, strlen($num)-3, strlen($num)); $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping. $expunit = str_split($restunits, 2); for($i=0; $i<sizeof($expunit); $i++) { // creates each of the 2's group and adds a comma to the end if($i==0) { $explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer } else { $explrestunits .= $expunit[$i].","; } } $thecash = $explrestunits.$lastthree; } else { $thecash = $num; } return $thecash; // writes the final format where $currency is the currency symbol. }
$num = 1234567890.123; $num = preg_replace("/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/i", "$1,", $num); echo $num; // Input : 1234567890.123 // Output : 1,23,45,67,890.123 // Input : -1234567890.123 // Output : -1,23,45,67,890.123
echo 'Rs. '.IND_money_format(1234567890); function IND_money_format($money){ $len = strlen($money); $m = ''; $money = strrev($money); for($i=0;$i<$len;$i++){ if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$len){ $m .=','; } $m .=$money[$i]; } return strrev($m); } NOTE:: it is not tested on float values and it suitable for only Integer
The example you've linked is making use of the ICU libraries which are available with PHP in the intl ExtensionDocs: $fmt = new NumberFormatter($locale = 'en_IN', NumberFormatter::CURRENCY); echo $fmt->format(10000000000.1234)."\n"; # Rs 10,00,00,00,000.12 Or maybe better fitting in your case: $fmt = new NumberFormatter($locale = 'en_IN', NumberFormatter::DECIMAL); echo $fmt->format(10000000000)."\n"; # 10,00,00,00,000
Simply use below function to format in INR. function amount_inr_format($amount) { $fmt = new \NumberFormatter($locale = 'en_IN', NumberFormatter::DECIMAL); return $fmt->format($amount); }
Check this code, it works 100% for Indian Rupees format with decimal format. You can use numbers like : 123456.789 123.456 123.4 123 and 1,2,3,4,5,6,7,8,9,.222 function moneyFormatIndia($num){ $explrestunits = "" ; $num = preg_replace('/,+/', '', $num); $words = explode(".", $num); $des = "00"; if(count($words)<=2){ $num=$words[0]; if(count($words)>=2){$des=$words[1];} if(strlen($des)<2){$des="$des";}else{$des=substr($des,0,2);} } if(strlen($num)>3){ $lastthree = substr($num, strlen($num)-3, strlen($num)); $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping. $expunit = str_split($restunits, 2); for($i=0; $i<sizeof($expunit); $i++){ // creates each of the 2's group and adds a comma to the end if($i==0) { $explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer }else{ $explrestunits .= $expunit[$i].","; } } $thecash = $explrestunits.$lastthree; } else { $thecash = $num; } return "$thecash.$des"; // writes the final format where $currency is the currency symbol. }
When money_format is not available : function format($amount): string { list ($number, $decimal) = explode('.', sprintf('%.2f', floatval($amount))); $sign = $number < 0 ? '-' : ''; $number = abs($number); for ($i = 3; $i < strlen($number); $i += 3) { $number = substr_replace($number, ',', -$i, 0); } return $sign . $number . '.' . $decimal; }
<?php $amount = '-100000.22222'; // output -1,00,000.22 //$amount = '0100000.22222'; // output 1,00,000.22 //$amount = '100000.22222'; // output 1,00,000.22 //$amount = '100000.'; // output 1,00,000.00 //$amount = '100000.2'; // output 1,00,000.20 //$amount = '100000.0'; // output 1,00,000.00 //$amount = '100000'; // output 1,00,000.00 echo $aaa = moneyFormatIndia($amount); function moneyFormatIndia($amount) { $amount = round($amount,2); $amountArray = explode('.', $amount); if(count($amountArray)==1) { $int = $amountArray[0]; $des=00; } else { $int = $amountArray[0]; $des=$amountArray[1]; } if(strlen($des)==1) { $des=$des."0"; } if($int>=0) { $int = numFormatIndia( $int ); $themoney = $int.".".$des; } else { $int=abs($int); $int = numFormatIndia( $int ); $themoney= "-".$int.".".$des; } return $themoney; } function numFormatIndia($num) { $explrestunits = ""; if(strlen($num)>3) { $lastthree = substr($num, strlen($num)-3, strlen($num)); $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping. $expunit = str_split($restunits, 2); for($i=0; $i<sizeof($expunit); $i++) { // creates each of the 2's group and adds a comma to the end if($i==0) { $explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer } else { $explrestunits .= $expunit[$i].","; } } $thecash = $explrestunits.$lastthree; } else { $thecash = $num; } return $thecash; // writes the final format where $currency is the currency symbol. } ?>
So if I'm reading that right, the Indian Numbering System separates the thousands, then every power of a hundred past that? Hmm... Perhaps something like this? function indian_number_format($num) { $num = "".$num; if( strlen($num) < 4) return $num; $tail = substr($num,-3); $head = substr($num,0,-3); $head = preg_replace("/\B(?=(?:\d{2})+(?!\d))/",",",$head); return $head.",".$tail; }
$amount=-3000000000111.11; $amount<0?(($sign='-').($amount*=-1)):$sign=''; //Extracting sign from given amount $pos=strpos($amount, '.'); //Identifying the decimal point position $amt= substr($amount, $pos-3); // Extracting last 3 digits of integer part along with fractional part $amount= substr($amount,0, $pos-3); //removing the extracted part from amount for(;strlen($amount);$amount=substr($amount,0,-2)) // Now loop through each 2 digits of remaining integer part $amt=substr ($amount,-2).','.$amt; //forming Indian Currency format by appending (,) for each 2 digits echo $sign.$amt; //Appending sign
I think this a quick and simplest solution:- function formatToInr($number){ $number=round($number,2); // windows is not supported money_format if(setlocale(LC_MONETARY, 'en_IN')){ return money_format('%!'.$decimal.'n', $number); } else { if(floor($number) == $number) { $append='.00'; }else{ $append=''; } $number = preg_replace("/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/i", "$1,", $number); return $number.$append; } }
You should check the number_format function.Here is the link Separating thousands with commas will look like $rupias = number_format($number, 2, ',', ',');
I have used different format parameters to money_format() for my output. setlocale(LC_MONETARY, 'en_IN'); if (ctype_digit($amount) ) { // is whole number // if not required any numbers after decimal use this format $amount = money_format('%!.0n', $amount); } else { // is not whole number $amount = money_format('%!i', $amount); } //$amount=10043445.7887 outputs 1,00,43,445.79 //$amount=10043445 outputs 1,00,43,445
Above Function Not working with Decimal $amount = 10000034000.001; $amount = moneyFormatIndia( $amount ); echo $amount; function moneyFormatIndia($num){ $nums = explode(".",$num); if(count($nums)>2){ return "0"; }else{ if(count($nums)==1){ $nums[1]="00"; } $num = $nums[0]; $explrestunits = "" ; if(strlen($num)>3){ $lastthree = substr($num, strlen($num)-3, strlen($num)); $restunits = substr($num, 0, strlen($num)-3); $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; $expunit = str_split($restunits, 2); for($i=0; $i<sizeof($expunit); $i++){ if($i==0) { $explrestunits .= (int)$expunit[$i].","; }else{ $explrestunits .= $expunit[$i].","; } } $thecash = $explrestunits.$lastthree; } else { $thecash = $num; } return $thecash.".".$nums[1]; } } Answer : 10,00,00,34,000.001
It's my very own function to do the task function bd_money($num) { $pre = NULL; $sep = array(); $app = '00'; $s=substr($num,0,1); if ($s=='-') {$pre= '-';$num = substr($num,1);} $num=explode('.',$num); if (count($num)>1) $app=$num[1]; if (strlen($num[0])<4) return $pre . $num[0] . '.' . $app; $th=substr($num[0],-3); $hu=substr($num[0],0,-3); while(strlen($hu)>0){$sep[]=substr($hu,-2); $hu=substr($hu,0,-2);} return $pre.implode(',',array_reverse($sep)).','.$th.'.'.$app; } It took 0.0110 Seconds per THOUSAND query while number_format took 0.001 only. Always try to use PHP native functions only when performance is target issue.
$r=explode('.',12345601.20); $n = $r[0]; $len = strlen($n); //lenght of the no $num = substr($n,$len-3,3); //get the last 3 digits $n = $n/1000; //omit the last 3 digits already stored in $num while($n > 0) //loop the process - further get digits 2 by 2 { $len = strlen($n); $num = substr($n,$len-2,2).",".$num; $n = round($n/100); } echo "Rs.".$num.'.'.$r[1];
If you dont want to use any inbuilt function in my case i was doing on iis server so was unable to use one the function in php so did this $num = -21324322.23; moneyFormatIndiaPHP($num); function moneyFormatIndiaPHP($num){ //converting it to string $numToString = (string)$num; //take care of decimal values $change = explode('.', $numToString); //taking care of minus sign $checkifminus = explode('-', $change[0]); //if minus then change the value as per $change[0] = (count($checkifminus) > 1)? $checkifminus[1] : $checkifminus[0]; //store the minus sign for further $min_sgn = ''; $min_sgn = (count($checkifminus) > 1)?'-':''; //catch the last three $lastThree = substr($change[0], strlen($change[0])-3); //catch the other three $ExlastThree = substr($change[0], 0 ,strlen($change[0])-3); //check whethr empty if($ExlastThree != '') $lastThree = ',' . $lastThree; //replace through regex $res = preg_replace("/\B(?=(\d{2})+(?!\d))/",",",$ExlastThree); //main container num $lst = ''; if(isset($change[1]) == ''){ $lst = $min_sgn.$res.$lastThree; }else{ $lst = $min_sgn.$res.$lastThree.".".$change[1]; } //special case if equals to 2 then if(strlen($change[0]) === 2){ $lst = str_replace(",","",$lst); } return $lst; }
This for both integer and float values function indian_money_format($number) { if(strstr($number,"-")) { $number = str_replace("-","",$number); $negative = "-"; } $split_number = #explode(".",$number); $rupee = $split_number[0]; $paise = #$split_number[1]; if(#strlen($rupee)>3) { $hundreds = substr($rupee,strlen($rupee)-3); $thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3)); $thousands = ''; for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2) { $thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].","; } $thousands = strrev(trim($thousands,",")); $formatted_rupee = $thousands.",".$hundreds; } else { $formatted_rupee = $rupee; } if((int)$paise>0) { $formatted_paise = ".".substr($paise,0,2); }else{ $formatted_paise = '.00'; } return $negative.$formatted_rupee.$formatted_paise; }
Use this function: function addCommaToRs($amt, &$ret, $dec='', $sign=''){ if(preg_match("/-/",$amt)){ $amts=explode('-',$amt); $amt=$amts['1']; static $sign='-'; } if(preg_match("/\./",$amt)){ $amts=explode('.',$amt); $amt=$amts['0']; $l=strlen($amt); static $dec; $dec=$amts['1']; } else { $l=strlen($amt); } if($l>3){ if($l%2==0){ $ret.= substr($amt,0,1); $ret.= ","; addCommaToRs(substr($amt,1,$l),$ret,$dec); } else{ $ret.=substr($amt,0,2); $ret.= ","; addCommaToRs(substr($amt,2,$l),$ret,$dec); } } else { $ret.= $amt; if($dec) $ret.=".".$dec; } return $sign.$ret; } Call it like this: $amt = ''; echo addCommaToRs(123456789.123,&$amt,0); This will return 12,34,567.123.
<?php function moneyFormatIndia($num) { //$num=123456789.00; $result=''; $sum=explode('.',$num); $after_dec=$sum[1]; $before_dec=$sum[0]; $result='.'.$after_dec; $num=$before_dec; $len=strlen($num); if($len<=3) { $result=$num.$result; } else { if($len<=5) { $result='Rs '.substr($num, 0,$len-3).','.substr($num,$len-3).$result; return $result; } else { $ls=strlen($num); $result=substr($num, $ls-5,2).','.substr($num, $ls-3).$result; $num=substr($num, 0,$ls-5); while(strlen($num)!=0) { $result=','.$result; $ls=strlen($num); if($ls<=2) { $result='Rs. '.$num.$result; return $result; } else { $result=substr($num, $ls-2).$result; $num=substr($num, 0,$ls-2); } } } } } ?>
heres is simple thing u can do , float amount = 100000; NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN")); String moneyString = formatter.format(amount); System.out.println(moneyString); The output will be , Rs.100,000.00 .
declare #Price decimal(26,7) Set #Price=1234456677 select FORMAT(#Price, 'c', 'en-In') Result: 1,23,44,56,677.00
Parsing EXIF's "ExposureTime" using PHP
Re, One photo with exposure being 1/640 has the EXIF field of "ExposureTime" eq. "15625/10000000". I am not sure why some photos display this value in a readable format (e.g., "1/100"), but I need to convert this "15625" back to "1/640". How? :) Thanks.
It's simple mathematics: simply divide the top and bottom of the fraction by the top value. 15625 / 10000000 = (15625/15625) / (10000000/15625) = 1 / 640 In PHP, you can do it like this: $exposure = "15625/10000000"; $parts = explode("/", $exposure); $exposure = implode("/", array(1, $parts[1]/$parts[0])); echo $exposure;
I improved upon ZZ Coders implementation with a few sanity checks and special cases. It seems to work well with my images with several special cases thrown at it. Please let me know if there are any issues and we'll improve it. // Exposure Time $exif = exif_read_data($fullPath, 'IFD0', true); $arrExposureTime = explode('/', $exif['EXIF']['ExposureTime']); // Sanity check for zero denominator. if ($arrExposureTime[1] == 0) { $ExposureTime = '<sup>1</sup>/? sec'; // In case numerator is zero. } elseif ($arrExposureTime[0] == 0) { $ExposureTime = '<sup>0</sup>/' . $arrExposureTime[1] . ' sec'; // When denominator is 1, display time in whole seconds, minutes, and/or hours. } elseif ($arrExposureTime[1] == 1) { // In the Seconds range. if ($arrExposureTime[0] < 60) { $ExposureTime = $arrExposureTime[0] . ' s'; // In the Minutes range. } elseif (($arrExposureTime[0] >= 60) && ($arrExposureTime[0] < 3600)) { $ExposureTime = gmdate("i\m:s\s", $arrExposureTime[0]); // In the Hours range. } else { $ExposureTime = gmdate("H\h:i\m:s\s", $arrExposureTime[0]); } // When inverse is evenly divisable, show reduced fractional exposure. } elseif (($arrExposureTime[1] % $arrExposureTime[0]) == 0) { $ExposureTime = '<sup>1</sup>/' . $arrExposureTime[1]/$arrExposureTime[0] . ' sec'; // If the value is greater or equal to 3/10, which is the smallest standard // exposure value that doesn't divid evenly, show it in decimal form. } elseif (($arrExposureTime[0]/$arrExposureTime[1]) >= 3/10) { $ExposureTime = round(($arrExposureTime[0]/$arrExposureTime[1]), 1) . ' sec'; // If all else fails, just display it as it was found. } else { $ExposureTime = '<sup>' . $arrExposureTime[0] . '</sup>/' . $arrExposureTime[1] . ' sec'; }
This is the code I use to normalize the exposure, if (($bottom % $top) == 0) { $data = '1/'.round($bottom/$top, 0).' sec'; } else { if ($bottom == 1) { $data = $top.' sec'; } else { $data = $top.'/'.$bottom.' sec'; } } It handles most exposures correctly but I see some weird ones once a while.
You can use Euclid's algorithm to find the greatest common divisor, which will help you reduce the fraction.