Defining cross-platform money_format function (Linux and Windows)

邮差的信 提交于 2020-01-21 04:50:43

问题


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


来源:https://stackoverflow.com/questions/9974704/defining-cross-platform-money-format-function-linux-and-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!