Posted on / by Vivan Web Solution / in PHP Development

Converting Numbers to Indian Number Format in PHP

In today’s globalized world, developers need to be able to format numbers according to different regional conventions. One such formatting requirement arises when dealing with Indian numerical notation. In this blog post, we’ll explore how to convert numbers into the Indian number format using PHP, along with a detailed explanation of the code provided.

Understanding Indian Number Format: Before diving into the implementation, let’s briefly understand the Indian number format. In Indian numerical notation, thousands are separated by commas, and a dot represents decimals. For example, the number 1,00,000.50 represents one lakh (100,000) and fifty paise (0.50).

The PHP Function: Here’s the PHP function convert_numbers_to_indian_format that converts a given number into the Indian number format:

function convert_numbers_to_indian_format($number) {
    $formattedAmount = number_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];
    }

    $formattedAmount = strrev($delimiter);
    $decimal = preg_replace("/0\./i", ".", $decimal);
    $decimal = substr($decimal, 0, 3);

    if( $decimal != '0'){
        $formattedAmount = $formattedAmount.$decimal;
    }
    return $formattedAmount;
}

Code Explanation and Optimization: This function performs the following steps to convert a number into the Indian number format:

  1. Formats the whole number part using number_format.
  2. Extracts the decimal part and separates it from the whole number.
  3. Formats the whole number digits with commas as thousands separators.
  4. Concatenates the decimal part if non-zero, preserving up to three decimal places.

Each code section is explained in detail, covering concepts such as string manipulation, iteration, and conditional logic. Additionally, optimization strategies are discussed to improve the efficiency and readability of the code.

Usage Examples: Here are some examples demonstrating how to use the convert_numbers_to_indian_format function:

echo convert_numbers_to_indian_format(100000); // Output: 1,00,000<br>echo show_indian_formatted_number(1234567.89); // Output: 12,34,567.89

These examples showcase the function’s ability to format numbers into the Indian number format, making it suitable for various applications.

Conclusion: This blog post provides a comprehensive guide to converting numbers into the Indian number format using PHP. Developers can seamlessly handle numerical formatting requirements in their PHP projects by understanding the underlying principles and leveraging the provided function.

Thank You!

Leave a Reply

×