Skip to content

Instantly share code, notes, and snippets.

@ruturajpatki
Created January 24, 2024 16:21
Show Gist options
  • Select an option

  • Save ruturajpatki/092ea2a8f407df442bbe2086c4b20884 to your computer and use it in GitHub Desktop.

Select an option

Save ruturajpatki/092ea2a8f407df442bbe2086c4b20884 to your computer and use it in GitHub Desktop.
Pure PHP implementation to format any given number in Indian Currency Format.
function formatIndianCurrency($number) {
// Step 0: Check if the number is negative
$isNegativeNumber = false;
if ($number < 0) {
$isNegativeNumber = true;
$number = abs($number);
}
// Step 1: Check for decimal point
if (strpos($number, '.') !== false) {
list($wholeNumber, $decimalNumber) = explode('.', $number);
} else {
$wholeNumber = $number;
$decimalNumber = '';
}
// Step 2: Check length of wholeNumber
if (strlen($wholeNumber) < 3) {
$result = $wholeNumber . ($decimalNumber ? '.' . $decimalNumber : '');
} else {
// Step 3: Split into hundredsNumber and otherNumber
$hundredsNumber = substr($wholeNumber, -3);
$otherNumber = substr($wholeNumber, 0, -3);
// Step 4: Process otherNumber in reverse
$otherNumberArray = str_split(strrev($otherNumber));
$finalOtherNumber = '';
foreach ($otherNumberArray as $index => $char) {
$finalOtherNumber = $char . $finalOtherNumber;
if ($index % 2 == 1 && $index < count($otherNumberArray) - 1) {
$finalOtherNumber = ',' . $finalOtherNumber;
}
}
// Step 5: Concatenate and return the result
$result = '₹' . (($finalOtherNumber == '') ? '' : $finalOtherNumber . ',') . $hundredsNumber . ($decimalNumber ? '.' . $decimalNumber : '');
}
// Check if the number was originally negative
if ($isNegativeNumber) {
$result = '-' . $result;
}
return $result;
}
@ruturajpatki
Copy link
Author

ruturajpatki commented Jul 20, 2024

Formatting Numbers into Indian Currency Format using Python

We will write a Python function to format numbers into the Indian currency format. Indian currency formatting is unique as it uses commas differently compared to other numbering systems. For instance, the number 123456789 is formatted as 12,34,56,789 in Indian currency.

Step 1: Converting the Number to a String

First, we need to convert the input number to a string. This allows us to easily manipulate and format the number.

def format_indian_currency(number: float) -> str:
    # Convert the number to a string
    number = str(number)

This initial step ensures that we are working with a string representation of the number, making it easier to handle subsequent formatting operations.

Step 2: Splitting the Number into Integer and Decimal Parts

Next, we need to check if the number has a decimal point. If it does, we split the number into integer and decimal parts. If not, we just keep the integer part.

    # Check if the number has a decimal point
    if '.' in number:
        # Split the number into integer and decimal parts
        integer, decimal = number.split('.')
    else:
        integer = number
        decimal = ''

This step helps us manage numbers with and without decimal points separately, ensuring accurate formatting for both types.

Step 3: Handling the Integer Part

We then convert the integer part into a character array for easy manipulation.

    # Convert the integer part into a character array
    chars = list(integer)

If the length of the integer part is less than or equal to 3, we don't need to format it further.

    # If the length is less than or equal to 3, output the number as is
    if len(chars) <= 3:
        formatted_number = integer
    else:
        # Formatting logic

This conditional check allows us to bypass unnecessary formatting for shorter numbers.

Step 4: Formatting the Integer Part

For numbers longer than 3 digits, we first get the last 3 digits and then process the remaining digits.

        # Get the last 3 digits
        formatted_number = integer[-3:]
        
        # Remove the last 3 digits from the array
        chars = chars[:-3]

We then traverse the remaining digits in reverse order, adding a comma after every 2 digits.

        # Traverse the array in reverse order and add comma after every 2 digits
        index = len(chars)
        while index > 0:
            index -= 2
            formatted_number = ''.join(chars[max(0, index):index + 2]) + ',' + formatted_number

This loop ensures that commas are inserted in the correct positions according to the Indian numbering system.

Step 5: Adding the Decimal Part

Finally, if the number has a decimal part, we append it to the formatted number.

    # Append the decimal part if it exists
    if decimal:
        formatted_number += '.' + decimal

This step ensures that any fractional part of the number is preserved in the final formatted output.

Step 6: Returning the Formatted Number

The function then returns the formatted number.

    return formatted_number

Here is the complete function:

def format_indian_currency(number: float) -> str:
    number = str(number)
    if '.' in number:
        integer, decimal = number.split('.')
    else:
        integer = number
        decimal = ''
    chars = list(integer)
    if len(chars) <= 3:
        formatted_number = integer
    else:
        formatted_number = integer[-3:]
        chars = chars[:-3]
        index = len(chars)
        while index > 0:
            index -= 2
            formatted_number = ''.join(chars[max(0, index):index + 2]) + ',' + formatted_number
    if decimal:
        formatted_number += '.' + decimal
    return formatted_number

Testing the Function

Let’s test the function with some examples to see how it works.

print(format_indian_currency(123456789))        # Output: 12,34,56,789
print(format_indian_currency(123456789.123))    # Output: 12,34,56,789.123
print(format_indian_currency(123))              # Output: 123
print(format_indian_currency(1234))             # Output: 1,234
print(format_indian_currency(12345.67))         # Output: 12,345.67

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment