Formatting price in INR method - php

I have a piece of code, which formats a number to INR Price (₹1.00/- , ₹10,00,000.00/- , etc.):
function price_format($num,$type = 1){
$num_full = number_format($num,2);
if (strpos($num, '.') !== false) {
$num = substr($num_full, 0, strpos($num_full, "."));
}
if($type == 1){ // '₹10,00,000.00/-'
$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.substr($num_full, -3, strpos($num_full, "."))."/-";
} else {
$thecash = "₹".$num.substr($num_full, -3, strpos($num_full, "."))."/-";
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
}
For the below test, it is not giving as expected result.
echo price_format(1)."<br />";
echo price_format(10)."<br />";
echo price_format(84289.35);
Live Demo
Also, the code is open and I am happy if someone wants to have this code more clear and short

There is no use of strpos while setting the value to $thecash. strpos doc
Use number_format() as: number_format((float)$num,2,'.','');
Working Code:-
function price_format($num,$type = 1){
$num_full = number_format((float)$num,2,'.','');
if (strpos($num, '.') !== false) {
$num = substr($num_full, 0, strpos($num_full, "."));
}
if($type == 1){ // '₹10,00,000.00/-'
$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.substr($num_full, -3)."/-";
} else {
$thecash = "₹".$num.substr($num_full, -3)."/-";
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
}
echo price_format(1).PHP_EOL;
echo price_format(10).PHP_EOL;
echo price_format(84289.35);

Related

How to convert word to number using my function?

I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.

How can I remove last digit from decimal number in PHP

I want to remove last digit from decimal number in PHP.
Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.
I think this should work:
<?php
$num = 14.153;
$strnum = (string)$num;
$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;
$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3
if($decimalPoints > 0)
{
for($i=0 ; $i<=$decimalPoints ; $i++)
{
// substring($strnum, 0, 0); causes an empty result so we want to avoid it
if($i > 0)
{
echo substr($strnum, 0, '-'.$i).'<br>';
}
else
{
echo $strnum.'<br>';
}
}
}
?>
echo round(14.153, 2); // 14.15
The round second parameter sets the number of digits.
You can try this.
Live DEMO
<?php
$number = 14.153;
echo number_format($number,2);

Validate IBAN PHP

As designing a new platform we tried to integrate the IBAN numbers. We have to make sure that the IBAN is validated and the IBAN stored to the database is always correct. So what would be a proper way to validate the number?
As the logic was explained in my other question, I've created a function myself. Based on the logic explained in the Wikipedia article find a proper function below. Country specific validation.
Algorithm and character lengths per country at https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN.
function checkIBAN($iban)
{
if(strlen($iban) < 5) return false;
$iban = strtolower(str_replace(' ','',$iban));
$Countries = array('al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24);
$Chars = array('a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35);
if(array_key_exists(substr($iban,0,2), $Countries) && strlen($iban) == $Countries[substr($iban,0,2)]){
$MovedChar = substr($iban, 4).substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach($MovedCharArray AS $key => $value){
if(!is_numeric($MovedCharArray[$key])){
if(!isset($Chars[$MovedCharArray[$key]])) return false;
$MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
}
$NewString .= $MovedCharArray[$key];
}
if(bcmod($NewString, '97') == 1)
{
return true;
}
}
return false;
}
Slight modification of #PeterFox answer including support for bcmod() when bcmath is not available,
<?php
function isValidIBAN ($iban) {
$iban = strtolower($iban);
$Countries = array(
'al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,
'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,
'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,
'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,
'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24
);
$Chars = array(
'a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,
'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35
);
if (strlen($iban) != $Countries[ substr($iban,0,2) ]) { return false; }
$MovedChar = substr($iban, 4) . substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach ($MovedCharArray as $k => $v) {
if ( !is_numeric($MovedCharArray[$k]) ) {
$MovedCharArray[$k] = $Chars[$MovedCharArray[$k]];
}
$NewString .= $MovedCharArray[$k];
}
if (function_exists("bcmod")) { return bcmod($NewString, '97') == 1; }
// http://au2.php.net/manual/en/function.bcmod.php#38474
$x = $NewString; $y = "97";
$take = 5; $mod = "";
do {
$a = (int)$mod . substr($x, 0, $take);
$x = substr($x, $take);
$mod = $a % $y;
}
while (strlen($x));
return (int)$mod == 1;
}
The accepted answer is not the preferred way of validation. The specification dictates the following:
Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid
Replace the two check digits by 00 (e.g. GB00 for the UK)
Move the four initial characters to the end of the string
Replace the letters in the string with digits, expanding the string as necessary, such that A or a = 10, B or b = 11, and Z or z = 35. Each alphabetic character is therefore replaced by 2 digits
Convert the string to an integer (i.e. ignore leading zeroes)
Calculate mod-97 of the new number, which results in the remainder
Subtract the remainder from 98, and use the result for the two check digits. If the result is a single digit number, pad it with a leading 0 to make a two-digit number
I've written a class that validates, formats and parses strings according to the spec. Hope this helps some save the time required to roll their own.
The code can be found on GitHub here.
top rated function does NOT work.
Just try a string with '%' in it...
I'm using this one :
function checkIBAN($iban) {
// Normalize input (remove spaces and make upcase)
$iban = strtoupper(str_replace(' ', '', $iban));
if (preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $iban)) {
$country = substr($iban, 0, 2);
$check = intval(substr($iban, 2, 2));
$account = substr($iban, 4);
// To numeric representation
$search = range('A','Z');
foreach (range(10,35) as $tmp)
$replace[]=strval($tmp);
$numstr=str_replace($search, $replace, $account.$country.'00');
// Calculate checksum
$checksum = intval(substr($numstr, 0, 1));
for ($pos = 1; $pos < strlen($numstr); $pos++) {
$checksum *= 10;
$checksum += intval(substr($numstr, $pos,1));
$checksum %= 97;
}
return ((98-$checksum) == $check);
} else
return false;
}
I found this solution in cakephp 3.7 validation class. Plain beautiful php realization.
/**
* Check that the input value has a valid International Bank Account Number IBAN syntax
* Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots,
* body matches against checksum via Mod97-10 algorithm
*
* #param string $check The value to check
*
* #return bool Success
*/
public static function iban($check)
{
if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $check)) {
return false;
}
$country = substr($check, 0, 2);
$checkInt = intval(substr($check, 2, 2));
$account = substr($check, 4);
$search = range('A', 'Z');
$replace = [];
foreach (range(10, 35) as $tmp) {
$replace[] = strval($tmp);
}
$numStr = str_replace($search, $replace, $account . $country . '00');
$checksum = intval(substr($numStr, 0, 1));
$numStrLength = strlen($numStr);
for ($pos = 1; $pos < $numStrLength; $pos++) {
$checksum *= 10;
$checksum += intval(substr($numStr, $pos, 1));
$checksum %= 97;
}
return ((98 - $checksum) === $checkInt);
}
This function check the IBAN and need GMP activate http://php.net/manual/en/book.gmp.php.
function checkIban($string){
$to_check = substr($string, 4).substr($string, 0,4);
$converted = '';
for ($i = 0; $i < strlen($to_check); $i++){
$char = strtoupper($to_check[$i]);
if(preg_match('/[0-9A-Z]/',$char)){
if(!preg_match('/\d/',$char)){
$char = ord($char)-55;
}
$converted .= $char;
}
}
// prevent: "gmp_mod() $num1 is not an integer string" error
$converted = ltrim($converted, '0');
return strlen($converted) && gmp_strval(gmp_mod($converted, '97')) == 1;
}
enjoy !

auto increasing id

I would like to build a php script that automatically generates a new id by increasing the previous by 1.
eg: A0009 becomes A0010 and A9999 becomes B0000
I have written one that works but it doesn't go over 5 chars long:
eg: Z9999 should go to A00000 and so on.
Any suggestions?
here is my snippet:
<?php
function replaceChar($string2replace)
{
$charLength = strlen($string2replace)-1;
$charAt = array();
$charAt[4] = substr($string2replace, -1);
$charAt[3] = substr($string2replace, -2,1);
$charAt[2] = substr($string2replace, -3,1);
$charAt[1] = substr($string2replace, -4,1);
$charAt[0] = substr($string2replace, 0,1);
if($charAt[4] < 9)
{
$string2replace = substr_replace($string2replace,$charAt[4]+1,$charLength);
}
else
{
$charAt[4] = 0;
$string2replace = substr_replace($string2replace,$charAt[4],$charLength);
if($charAt[3] < 9)
{
$string2replace = substr_replace($string2replace,$charAt[3]+1,$charLength- 1,1);
}
else
{
$charAt[3] = 0;
$string2replace = substr_replace($string2replace,$charAt[3],$charLength-1,1);
if($charAt[2] < 9)
{
$string2replace = substr_replace($string2replace,$charAt[2]+1,$charLength-2,1);
}
else
{
$charAt[2] = 0;
$string2replace = substr_replace($string2replace,$charAt[2],$charLength-2,1);
if($charAt[1] < 9)
{
$string2replace = substr_replace($string2replace,$charAt[1]+1,$charLength-3,1);
}
else
{
$charAt[1] = 0;
$string2replace = substr_replace($string2replace,$charAt[1],$charLength-3,1);
}
if($charAt[0] < 'z')
{
$charAt[0] ++;
$string2replace = substr_replace($string2replace,$charAt[0],$charLength-4,1);
}
else
{
$charAt[0] = 'a';
$string2replace = substr_replace($string2replace,$charAt[0],$charLength-4,1);
}
}
}
}
return $string2replace;
}
$string2begin = 'A9999';
$generatedString = replaceChar($string2begin);
echo $string2begin . "<br />" . $generatedString;
?>
Your ID numbering scheme seems rather contrived, where the high-order digit is A-Z and the remaining digits are 0-9. If I understand that pattern correctly, this seems to do the trick:
function incrementID($id)
{
$letter = $id[0];
$number = substr($id, 1);
$newNum = str_pad($number + 1, strlen($number), '0', STR_PAD_LEFT);
// increase number only
if (strlen($number) == strlen($newNum))
return $letter . $newNum;
// increase ID length ('Z' to 'A')
if ($letter == 'Z')
return 'A' . str_repeat('0', strlen($number) + 1);
// change letter
$newLetter = chr(ord($letter) + 1);
return $newLetter . str_repeat('0', strlen($number));
}
printf("%s\n", incrementID('A0009')); // 'A0010'
printf("%s\n", incrementID('A9999')); // 'B0000'
printf("%s\n", incrementID('Z9999')); // 'A00000'
Even though your examples didn't fit this, I first assumed you really just wanted a base-36 number (any digit could be 0-9,A-Z, where A is 10 and Z is 35). Working with numbers in base-36 is easy because you can use base_convert() to convert them to customary base-10. This is all you would need to do to increment base-36 numbers:
function incrementBase36($id)
{
$numVal = base_convert($id, 36, 10);
$newId = base_convert($numVal + 1, 10, 36);
return strtoupper($newId);
}
printf("%s\n", incrementBase36('A0009')); // 'A000A'
printf("%s\n", incrementBase36('A9999')); // 'A999A'
printf("%s\n", incrementBase36('Z9999')); // 'Z999A'
printf("%s\n", incrementBase36('AZZZZ')); // 'B0000'
printf("%s\n", incrementBase36('ZZZZZ')); // '100000'

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 Extension­Docs:
$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

Categories