PHP JSON Format Currency Comma - php

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.

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'];

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'];

Related

Convert 8199000000 to decimal (php)

The API I fetch my data with, returns me 8199000000 for the price.
Which should be 81.99 but I should also expect something like 15499000000 which should result into 154.99.
How can I parse that clean and nice?
You can just divide by 1e8 (1 and 8 zeroes).
$price = 8199000000;
$real = $price / 1e8;
echo $real, PHP_EOL; // 81.99
$price = 15499000000;
$real = $price / 1e8;
echo $real, PHP_EOL; // 154.99
Nevermind I should have just used a regex.....
^([0-9]{2}|[0-9]{3})([0-9]{2})0

How to add commas and round decimals by checking value

I'm building an personal app where I can follow my cryptocurrency coins which I'm currently holding and following. The problem I've noticed are the decimals behind the price. A currency normally has max 2 decimals, but the API of Coinmarketcap gives me more depending on how much the price is.
Below is an example of the value I get from the API, and how I actually want the price to be shown. Values above 1000 will get a comma and no decimals.
$950194.0 -> $950,194
$81851.6 -> $81,852
$4364.97 -> $4,365
$326.024 -> $326.02
$35.0208 -> $35.02
$4.50548 -> $4.51
$0.0547128 -> $0.0547128
I've never tried something ever like this before, so I really don't know how to start. Tried using round() and numberFormat(), but couldn't make the same like how I wanted above in the example.
You can use money_format to make thing easier. However, the problem is about what precision do you want. You have to figure it out yourself since I cannot find the pattern from your examples. Yet I wrote the simple function for you with round and money_format. What the rest is adjust the precision to the point where you want in each case.
<?php
function my_money_format($number, $precision=0)
{
$number = preg_replace( '/[^0-9.,]/', '', $number); // clean the input
$number = round($number, $precision);
$format = '%.' . $precision . 'n';
setlocale(LC_MONETARY, 'en_US'); // set money format to US to use $
return money_format($format, $number);
}
echo my_money_format('$950194.0', 0); // $950,194
echo "\n";
echo my_money_format('$81851.6', 0); // $81,852
echo "\n";
echo my_money_format('$4364.97', 0); // $4,365
echo "\n";
echo my_money_format('$326.024', 2); // $326.02
echo "\n";
echo my_money_format('$35.0208', 2); // $35.02
echo "\n";
echo my_money_format('$4.50548', 2); // $4.51
echo "\n";
echo my_money_format('$0.0547128', 7); // $0.0547128
echo "\n";

Use my php variable as a formula to calculate something

I'm working in an invoice system, that has to calculate different formulas for every product, which will need to be filled with Width, Height, and Material cost.
I did a database where i'm storing
t_title -> "Curtain 1"
t_formula -> "({ANCHO}*{ALTURA})*{PRECIO}"
and then php does this:
<?php
$ancho = str_replace("{ANCHO}", $_POST['ancho'], $articulo['t_formula']);
$alto = str_replace("{ALTURA}", $_POST['alto'], $ancho);
$precio = str_replace("{PRECIO}", $_POST['precio'], $alto);
$total = $precio; echo eval($total);
?>
and the result is not giving anything, but a blank space.
How can i make it to work? I know that php can't calculate from variables as php but, i can't find another way to do it.
The eval() function expects the string parameter to be a proper code statement.
$str = '(10*10) * 1000';
echo eval($str);
will give you an error, because php cannot evaluate that string. However,
$str = 'return (10*10) * 1000;';
echo eval($str);
will evaluate the expression correctly.
You should use:
$total = 'return ' . $precio . ';';
echo eval($total);
Your using eval is wrong. The string passed to eval must be valid PHP code. i.e:
$precio2 = '$total = '.$precio.';';
eval($precio2);
echo $total;
http://php.net/manual/en/function.eval.php

PHP shopping cart calculation

Hi I need to remove 10% from a shopping carts subtotal
Original code:
<?php echo number_format($order->subtotal,2);?>&OID=<?php echo $order->trans_id;?>
I know it's not precise, but would something like this work?
<?php echo number_format($order->subtotal * 0.909090909,2);?>&OID=<?php echo $order->trans_id;?>
Thanks
Use sprintf()
$a = 2324.56*0.909090909 ;
echo sprintf('%0.2f',$a);
output // 2113.24
sprintf() will handle the floating point precession which is the best way to handle.
If needs to display the money format for specific locale it could be doing using money_format
$a = 2324.56*0.909090909 ;
$amount = sprintf('%0.2f',$a);
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#1n', $amount) . "\n";
output // $2,113.24
Here is an explanation on number_format() -ve value precession issue
http://www.howtoforge.com/php_number_format_and_a_problem_with_negative_values_rounded_to_zero
that probably would work, but why not just subtract the 10 percent? If that's the goal, why not just do it? keep in mind number_format rounds up, but I expect that's desired.
<?php echo number_format( ($order->subtotal - ($order->subtotal* .1) ) ,2);?>
This is the math that actually subtracts 10% why not use this instead of something that's close?
try this
$subtotal = $order->subtotal;
$cut_subtotal = $subtotal *(10/100);
$subtotal_new = $subtotal-$cut_subtotal;
Now use this in your code
<?php echo number_format($subtotal_new,2);?>

Calculating total price from string value in php

I have a e-commerce shop and on the shopping cart page it gives me a separate price for every product, but I need total price.
in order to do that, I need to calculate all these values together and that's fine.
But, what bugs me is that I should calculate the sum of variables that are given in this format:
$455.00
What is the best way to extract the value "455" so I could add it to another value afterwards?
I hope I made myself clear...
Don't use float, but instead use an integer in cent. Floats are not precise (see Floating Point Precision), so the calculation tend to fail if you use floats. That's especially a burden if it is related to payments.
$str = '$455.00';
$r = sscanf($str, '$%d.%d', $dollar, $cent);
if ($r <> 2 or $cent > 99 or $cent < 0 or $dollar > 9999 or $dollar < 0) throw new Exception(sprintf('Invalid string "%s"', $str));
$amountInDollarCents = $dollar * 100 + $cent;
echo $str, ' -> ', $amountInDollarCents;
Demo
If you need only the dollar sign removed, use str_replace. To convert that to int or float, typecast it. However, using float results in non-exact calculations so be careful with it!
$newval = (int)str_replace('$', '', '$455.00');
I think that your ECommerce site only has $ (USD)
$price= substr($string_price,1);
This will convert your string to a float:
$price = (float)substr("$455.00", 1);
echo($price);
For more information, you can see this answer, which has a couple of good links for you in it.
What about the following:
$amount = array();
$amount[0] = '$455.15';
$amount[2] = '$85.75';
$total = 0;
foreach ($amount AS $value) {
$value = str_replace('$', '', $value);
$total += $value;
}
echo $total . "\n";
The cleaning operation is:
$value = str_replace('$', '', $value);
You might want to extract it in a function, especially if you need to use it in more than one place.
Another thing to think about is, why do you have the value in such way? It's a display format and such conversion should be the last to be done, ideally by the template. Maybe, if possible, you should consider to fix the code before, instead of applying a patch like this one.
It really looks like your program is doing it wrong. You should really represent all prices as (double) instead of a string. Then only when you need to show the price to the user you would prepend the $ sign to it, converting it to a string. But your program should really treat prices as numbers and not strings.
If you storing your price in the database as a string "$5.99" then you are really doing it wrong.
It's been a long time since I worked with PHP, so I don't know what the best practice would be for working with currency. One quick method would be to remove "$" and ".", and just add together the resulting as integers.
use str_replace() for instance, and replace "$" and "." with an empty string: http://se2.php.net/manual/en/function.str-replace.php
This will give you the whole sum in cents (thus avoiding some potential rounding problems). You can then divide it by 100 and format it however you like to display the sum as dollars.

Categories