Search code examples
phpformattingnumbersnumber-formattingmoney-format

Defining cross-platform money_format function (Linux and Windows)


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?


Solution

  • 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