Defining cross-platform money_format function (Lin

2020-03-02 04:15发布

问题:

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 function, when available and using this workaround when not, so my library will be able to run on every PHP-based web server.

Is there any simple solution to check whether built-in function is available and if not to include the solution from above?

回答1:

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



回答2:

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;
    }
?>