Print Currency Number Format in PHP

后端 未结 7 790
野性不改
野性不改 2020-11-30 00:28

I have some price values to display in my page.

I am writing a function which takes the float price and returns the formatted currency val with currency code too..

相关标签:
7条回答
  • 2020-11-30 00:50

    with the intl extension in PHP 5.3+, you can use the NumberFormatter class:

    $amount = '12345.67';
    
    $formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
    echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
    
    $formatter = new NumberFormatter('de_DE',  NumberFormatter::CURRENCY);
    echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
    

    which prints :

     UK: €12,345.67
     DE: 12.345,67 €
    
    0 讨论(0)
  • 2020-11-30 00:52

    sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php

    I use this function:

    function formatDollars($dollars){
      return '$ '.sprintf('%0.2f', $dollars);
    }
    
    0 讨论(0)
  • 2020-11-30 00:53

    The easiest answer is number_format().

    echo "$ ".number_format($value, 2);
    

    If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00 for some of us Europeans for example), it becomes a bit more complex.

    There is money_format() but it doesn't work on Windows and relies on setlocale(), which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.

    If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.

    0 讨论(0)
  • 2020-11-30 00:56

    From the docs

    <?php
    
    $number = 1234.56;
    
    // english notation (default)
    $english_format_number = number_format($number);
    // 1,235
    
    // French notation
    $nombre_format_francais = number_format($number, 2, ',', ' ');
    // 1 234,56
    
    $number = 1234.5678;
    
    // english notation without thousands separator
    $english_format_number = number_format($number, 2, '.', '');
    // 1234.57
    
    ?>
    
    0 讨论(0)
  • 2020-11-30 00:58

    try

    echo "$".money_format('%i',$price);
    

    output will be

    $1.06

    0 讨论(0)
  • 2020-11-30 01:00

    PHP has a function called money_format for doing this. Read about this here.

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