views:

54

answers:

2

hi guys,

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..

like fnPrice(1001.01) should print $ 1,000.01

+4  A: 

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.

Pekka
+1 didn't know about those problems with Windows.
Sarfraz
RobertPitt
A: 

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);
}
Jim
this won't add commas (thousands separators)
stillstanding