Defining cross-platform money_format function (Linux and Windows)

前端 未结 2 565
一向
一向 2021-01-05 06:08

I have read that money_format is not available on windows, and on some Linux distributions (i.e. BSD 4.11 variants). But I want to write cross-platform library using normal

相关标签:
2条回答
  • 2021-01-05 06:27

    The money_format() is not worked on Windows machine. So here is your solution for Indian currency format:

    <?php
        function inr_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;
        }
    ?>
    
    0 讨论(0)
  • 2021-01-05 06:35

    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.

    So you can use this php code:

    setlocale(LC_ALL, ''); // Locale will be different on each system.
    $amount = 1000000.97;
    $locale = localeconv();
    echo $locale['currency_symbol'], number_format($amount, 2, $locale['decimal_point'], $locale['thousands_sep']);
    

    With this you can write code that is actually portable instead of relying on operating system features. Having the money_format function available in PHP without it being an extension is pretty stupid. I don’t see why you would want to create inconsistencies like this between different operating systems in a programming language

    0 讨论(0)
提交回复
热议问题