PDA

View Full Version : [Function] Currency_Format



Zero-Affect
06-09-2010, 06:02 PM
function currency_format($amount, $currency='') {
$currency_array = array(
'GBP' => '',
'JPY' => '',
'CNY' => '',
'EUR' => '',
'USD' => '$',
'' => ''
);
if ( (ctype_alpha($currency) OR empty($currency)) && array_key_exists($currency, $currency_array) && ctype_digit($amount) ) {
$ret_txt = '<span style="font-weight: bold;">'.$currency_array[$currency].'</span>'.number_format($amount);
} else {
$ret_txt = FALSE;
}
return $ret_txt;
}
$var = '2001';
echo currency_format($var, 'USD'); // outputs $2,001
echo currency_format($var, 'GBP'); // outputs 2,001
echo currency_format($var, 'JPY'); // outputs 2,001
echo currency_format($var, 'CNY'); // outputs 2,001
echo currency_format($var, 'EUR'); // outputs 2,001
echo currency_format($var); // outputs 2,001
echo currency_format($var, 'lol'); // fails
echo currency_format('+'.$var, 'USD'); // fails
I was bored and needed something like this so i made it and thought i'd post my result

Dillion & Amanda 4 Life!
06-09-2010, 06:06 PM
An even nicer function could be exchange rates, since All the currencies have different rates. It'd be cool if you could grab each one from a site that updates them, but current ones are fine

Zero-Affect
06-09-2010, 06:12 PM
I actually was thinking about doing a exchange rate one but the exchange rates are updated all the time there's not much point really.

Dillion & Amanda 4 Life!
06-09-2010, 07:26 PM
You know any sites with API's that you can grab the current exchange rate from?

LordDan
06-09-2010, 07:34 PM
function exchangeRate( $amount, $currency, $exchangeIn )
{
$googleQuery = $amount . ' ' . $currency . ' in ' . $exchangeIn;
$googleQuery = urlEncode( $googleQuery );
$askGoogle = file_get_contents( 'http://www.google.com/search?q=' . $googleQuery );
$askGoogle = strip_tags( $askGoogle );
$matches = array();
preg_match( '/= (([0-9]|\.|,|\ )*)/', $askGoogle, $matches );
return $matches[1] ? $matches[1] : false;
}

echo exchangeRate( 1000, 'euro', 'dollars' );


This what you mean?

Zero-Affect
06-10-2010, 12:21 PM
never thought of it that way, thanks for that LordDan

Dayo
06-10-2010, 04:45 PM
i made a function like this its in the mccodes free mods it has the conversion rate too

wops didnt see the auto updating

Karlos94
06-10-2010, 09:30 PM
Why not do it a nice simple way? Using a regularly updated XML file with the latest exchange rates, they aren't that hard to find. ;)

LordDan
06-10-2010, 10:02 PM
Because I didn't write it, I just did a search and posted as reference ^^ I've never needed such a function myself..

Karlos94
06-10-2010, 10:10 PM
Oh I see, but the idea is there now, in case someone wishes to do it the way I said.