Last active
June 19, 2024 05:10
-
-
Save SapneshNaik/94250492b8eaaf874773165782c9a3f5 to your computer and use it in GitHub Desktop.
A php function to convert a number into Indian Number System format (also Indian Currency Format)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function IND_money_format($number){ | |
$decimal = (string)($number - floor($number)); | |
$money = floor($number); | |
$length = strlen($money); | |
$delimiter = ''; | |
$money = strrev($money); | |
for($i=0;$i<$length;$i++){ | |
if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$length){ | |
$delimiter .=','; | |
} | |
$delimiter .=$money[$i]; | |
} | |
$result = strrev($delimiter); | |
$decimal = preg_replace("/0\./i", ".", $decimal); | |
$decimal = substr($decimal, 0, 3); | |
if( $decimal != '0'){ | |
$result = $result.$decimal; | |
} | |
return $result; | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How to add this as a global helper function in laravel? | |
1 - Create a `Helpers` directory for your helper functions in the app directory | |
`mkdir app/Helpers' . | |
2 - Download the `Indian_currency_format.php` file and save it to Helpers directory. | |
3 - In your composer.json add the file to "files" attribute of autoload so that it can be loaded by composer using PSR-4 autoloading | |
(see https://getcomposer.org/doc/04-schema.md#psr-4), | |
like so: | |
"autoload": { | |
"classmap": [ | |
"database/seeds", | |
"database/factories" | |
], | |
"psr-4": { | |
"App\\": "app/" | |
}, | |
"files": [ | |
"app/Helpers/IND_money_format.php" | |
] | |
}, | |
4 - Finally run `composer dump-autoload` to refresh autoload cache. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code gives an invalid output for an odd-digit negative number.
for eg. -96722 => -,96,722