A K
A K

Reputation: 97

PHP JSON Format Currency Comma

I'm new to PHP.

My code reads a price value from a Steam game's json data.

http://store.steampowered.com/api/appdetails/?appids=8870

Problem is that the value of the price node is not formatted with a comma separator for dollars and cents. My code works to piece together the dollars and cents but is it the right way to do it for this instance. Also if there is another easier method of doing my newbie code, feel free to show me where it can be improved. Thanks!

<?php

$appid = '8870';

$ht = 'http://store.steampowered.com/api/appdetails/?appids=' . $appid;

$fgc = file_get_contents($ht);
$jd = json_decode($fgc, true);

$gdata = $jd[$appid]['data'];

$gname = $gdata['name'];
$gprice = $gdata['price_overview']['final'];
$gdesc = $gdata['detailed_description'];

$gusd = substr($gprice, 0, -2);
$gcent = substr($gprice, 2);

echo $gname. '<br>';
echo 'Price: $' .$gusd. ',' .$gcent;

?>

If I may ask another question... can the price data aka $gprice be added to another price data that is fetched, to return a total.

Upvotes: 1

Views: 807

Answers (2)

fbiagi
fbiagi

Reputation: 826

The conversion is not bad, but you could also use this:

$gusd = $gprice/100;

echo $gname. '<br>';
echo 'Price: $' .str_replace('.', ',', $gusd);

or use money_format instead of replace, but it's a little more complicated.

also, to add another you could do it with just the + or += operators like this:

$gprice+= $gdata['price_overview']['final'];

Upvotes: 0

Rick Burgess
Rick Burgess

Reputation: 725

I would essentially do what you are doing except its much simpler to just divide by 100:

Turn the price into a float:

$gprice = $gprice / 100;

and then use money_format

Ref: PHP Docs - money_format

You could also do this, but there isn't really a need.

$gprice = (int) $gdata['price_overview']['final'];

Upvotes: 1

Related Questions