Monday, September 29, 2008

locale number formating

With money_format you can do great things to display the number.

// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, withouth grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// DEM 1234,56****

So it's very tempting to do

echo money_format('%!n',1234.56);

But the with the money function is that you either display decimals or you don't. I was looking for a function that has the possibility to only display decimals if the the number is floating.

After a few tries i came up with this

function locale_number($number,$decimals=2,$always_decimals=false)
{
if(is_int($number) && ! $always_decimals){ $decimals = 0; }
return number_format($number, $decimals, nl_langinfo(RADIXCHAR), nl_langinfo(THOUSEP));
}

I set the $always_decimals flag to FALSE because the money_format function will be faster if you always want to display decimals.

No comments: