Very short snippet: Currency format in PHP

Wednesday, February 11, 2009

PHP provides two convenient functions to format (and print) currencies money_format() and number_format() The first can be used together with setlocale() to set the formatting according to your country, for example:

PHP:
  1. 1234.56 ; $ number = 1234.56;
  2. LC_MONETARY , 'en_US' ) ; setlocale (LC_MONETARY, 'en_US');
  3. ( '%i' , $number ) ; echo money_format ( '% i', $ number);
  4. / / USD 1,234.56

For us Europeans, and Italians, we can use:

PHP:
  1. 1234.56 ; $ number = 1234.56;
  2. LC_MONETARY , 'it_IT' ) ; setlocale (LC_MONETARY, 'en_US');
  3. ( '%.2n' , $number ) ; echo money_format ( '% .2 n', $ number);
  4. / / U.S. $ 1234.56

However, in the simplest cases and if you bother EUR you can use:

PHP:
  1. 1234.56 ; $ number = 1234.56;
  2. ( $number , 2 , ',' , '.' ) echo number_format ($ number, 2, ',', '.')
  3. / / 1234.56

Related Post

Was this article helpful?: Per nientePocoAbbastanzaMoltoMoltissimo
Loading ... Loading ...

One comment to "Very short snippet: Currency format in PHP"

  1. getAvatar 1.0
    February 11, 2009 Luke:

    Shit I'd never seen money_format for php! thanks for the tip!

Leave a comment

TAG XHTML PERMISSIONS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre>         // blocco generico [code][/code]       // blocco generico [as][/as]           // Actionscript [css][/css]         // CSS Style Sheet [html][/html]       // HTML [js][/js]           // Javascript [objc][/objc]       // Objective-C [php][/php]         // PHP [sql][/sql]         // SQL