定义跨平台money_format函数(Linux和Windows)



我读到money_format在windows和一些Linux发行版(即BSD 4.11变体)上不可用。但我想在可用时使用正常函数编写跨平台库,在不可用时使用此解决方案,这样我的库将能够在每个基于PHP的web服务器上运行。

是否有任何简单的解决方案来检查内置功能是否可用,如果不包括上面的解决方案?

只有当系统具有strfmon功能时,才会定义函数money_format()。例如,Windows没有,因此money_format()在Windows中未定义。

因此,您可以使用以下php代码:

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']);

有了它,您可以编写实际可移植的代码,而不是依赖于操作系统功能。在PHP中提供money_format函数而不将其作为扩展是非常愚蠢的。我不明白你为什么要在编程语言

中的不同操作系统之间创建这样的不一致

money_format()不在Windows机器上工作。因此,以下是您的印度货币格式解决方案:

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

最新更新