I am trying to list the current USD price of an item in mBTC (millibitcoin) using the Coinbase API. Here is my code:
<?php
$string = file_get_contents('https://coinbase.com/api/v1/prices/spot_rate');
$result = json_decode($string);
$spot = $result->amount;
$price = 2; //change this to your USD value
$whole = substr($price/$spot, 4, -13);
$dec = substr($price/$spot, 4, -12);
echo $whole.'.'.$dec.' mBTC';
?>
It works flawlessly in Coderunner (OS X app for development) but fails when run on my hosting server. Link to browser script: http://bitcoindecals.com/oval-price.php
I am using Dynadot Advanced hosting and it includes PHP support. I know that PHP is being utilized because "mBTC" is being echoed correctly. It just appears the $whole and $dec variables aren't being set for some reason. Is there a way to get this to work?
You're making a few (extremly wrong) assumptions in the following lines:
$whole = substr($price/$spot, 4, -13);
$dec = substr($price/$spot, 4, -12);
$price / $spot is treated as a string and you assume it will be in the format
'0.0019XXXXXXXXXXXX' // 12 x's (unkown numbers)
What if Bitcoin is doing really bad and the rate exeeds 10 mBTC per USD? $price / $spot will be something like:
'0.0108491827849201'; // (10.8 mBTC)
$whole = substr('0.0108491827849201', 4, -13); // Will be '0'
$dec = substr('0.0108491827849201', 4, -12); // Will be '08'
echo $whole . '.' . $dec . ' mBTC'; // Will echo '0.08 mBTC'
What if, due to rounding or accuracy (! this is what you're seeing in your server - most likely because your OSX is 64bit, your server 32bit or vice-versa !), the string-length of $price / $spot is less than 18 characters:
'0.0019564521431';
$whole = substr('0.0019564521431', 4, -13);
// Meaning: start at position 4, stop at 13 characters counting from the end
// 13 characters from the end is here: '0.0019564521431'
// ^
// so the stop-position is before the start-position, resulting in an empty
// string. Same with $dec.
echo $whole . '.' . $dec . ' mBTC';
// Will echo empty-string . '.' . empty-string . ' mBTC': '. mBTC'
Long story short: never ever treat numbers as a string (unless you have no other options and you are fully aware of what you are doing). Following code will work, and will give the correct output:
echo number_format($price / $spot * 1000, 1);
// multiply by 1000: BTC to milli-BTC
// , 1: One digit after the dot
For a full explanation of number_format see: http://php.net/number_format
I just executed the exact code in my WAMP server on windows....
It seemed to work perfectly smooth !!!
OUTPUT : 1.19 mBTC Is it what you expect????
I think your server is unable to access web pages, so, your php code variables are going vacant...try XAMP and check out ....
Thanks....
you can't crawler the data from https://coinbase.com/api/v1/prices/spot_rate
so $string is empty!
do {
$string = file_get_contents('https://coinbase.com/api/v1/prices/spot_rate');
} while (!empty($string));
$result = json_decode($string);
$spot = $result->amount;
$price = 2; //change this to your USD value
if (isset($spot) or $spot == 0) {
echo "\$spot is not islet or 0";
} else {
$whole = substr($price/$spot, 4, -13);
$dec = substr($price/$spot, 4, -12);
echo $whole.'.'.$dec.' mBTC';
}
Related
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";
I have prices stored to five decimal places of precision, such as:
1.95000
2.25000
0.01150
2.10000
2.00000
When displaying prices, I'd like to show the standard $X.XX format if the rest of the digits are just zero, but if there are significant digits then I don't want to cut them out (so I can't simply use number_format()).
As an example, the above prices should display as:
1.95
2.25
0.0115
2.10
2.00
This process has to be done on hundreds of prices per page. What's an efficient way of formatting numbers in this manner?
This uses a regex to match everything before the trailing 0s
$i = "$1.00";
$pattern = '/\$(\d+)\.(\d\d)(0*)/';
$replacement = '\$$1.$2';
print preg_replace($pattern,$replacement,$i);
Another way using rtrim on everything after the first 2 digits right of the decimal
$pos = strpos($i, '.') + 3;
print substr($i, 0, $pos) . rtrim(substr($i, $pos), '0');
This is kind of ugly but it does the job:
function formatPrice($price) {
$out = (float)$price; // Trim off right-hand 0's
$out = "$out"; // Typecast back to string
if ((strlen($out) - strpos($out, '.')) <= 2) { // Test for string length after decimal point
$out = number_format($out, 2); // Format back with 0's
}
return $out;
}
Testing it now... Works!
Here's a one-liner function from my other comment thanks to #FuzzyTree's answer:
function formatPrice($price) {
return substr($price, 0, strpos($price, '.') + 3) . rtrim(substr($price, strpos($price, '.') + 3), '0');
}
I am sure this is because of the "g" on the end but this is the scenario and results when I try and work out a ratio percent. I always want to divide the highest of 2 numbers by the lowest.
$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"
$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"
PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"
It's type casting;
$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
result will be 175%
When you want to use your strings in mathematical operations, and you know that the unit is placed at the end as it is in your example, you can cast your variables to floats:
$item1_numeric = (float) $item1;
But obviously it is better to have the values and the units separated in your variables / database.
Use: substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.
You can't compare 2 strings with round().
Edit : If $item1 = "200g", ma solution is ok, but if if $item1 = "200.00g" you need to remove "." before round() with for example pregreplace.
Oh, YAPHPB - and one of my favorite ones. Even though it's written in the Doc:
When [max()] given a string it will be cast as an integer when comparing.
... it's only a partial truth: if at least one of compared values is a number, or a numeric string.
Otherwise all the strings will be compared as strings: first {0} characters of each strings will be compared, then {1}, then {2}... etc.
So basically that's what happens here:
echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
echo max("200.00g", 50); // "200.00g", as it gets converted to int (become 200)
And that's even more crazy:
echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
echo max("200.00", "1000.00"); // "1000.00", as we tried to help you, no, really!
The latter result can actually be predicted by someone knowing of numeric concept: when both strings are pure numbers, they got converted to numbers when compared. Still, I found this behavior unreliable, to say the least.
The bottom line: if you need to compare numbers, compare numbers, period. Type conversion in PHP can get real messy - and bite you in the bottom real hard when you least expect it. )
I have a price "0,10" or "00000,10"
Now when i try
number_format($price, 2, ',', '')
I get 0,00.
How can i fix this? I want 0,10 $.
I don't want rounding.
Or when i have 5,678, i get 5,68. But i want 5,67.
Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.
This is still not accurate, the best solution is this:
$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);
What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67
You can increase the size of the number before rounding down with floor:
$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');
Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:
$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
you should convert comma-filled number back to normal decimal before with str_replace.
$number = str_replace(",", ".", $number);
and then you can use number_format
"00000,10" is a string. You should a decimal point. To get the desired behaviour, you could use:
echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);
Use this (needs activated intl PHP extension)
$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
If you are literally just wanting to clear leading zeroes and just limit the length, rather than round to a certain amount of decimal places, a more generalised solution could be this function:
function cutafter($string,$cutpoint,$length)
{
$temp = explode($cutpoint,$string);
$int = $temp[0];
$sub = $temp[1];
return number_format($int,0).','.substr($sub,0,$length);
}
Example:
$number = "005,678";
$answer = cutafter($number,",",2);
$answer now equals "5,67"
Just before number_format is executed the string "0,10" is converted by php to an number. because php always uses the engish notation the it won't look after the comma.
echo "4 apples" + 2;
output: 6
The " apples" part is ignored just as your ",10" is ignored.
Converting the "," to a "." allows php to see the other digits.
$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');
My problem was that html validator error messege thar number_format() argument is not double.
I solved this error message by placing floatval for that argument like number_format(floatval($var),2,'.',' ') and that is working good.
function format_numeric($value) {
if (is_numeric($value)) { // is number
if (strstr($value, ".")) { // is decimal
$tmp = explode(".", $value);
$int = empty($tmp[0]) ? '0' : $tmp[0];
$dec = $tmp[1];
$value = number_format($int, 0) . "." . $dec;
return $value;
}
$value = number_format($value);
return $value;
}
return $value; // is string
}
Unit Testing:
Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc"
See this answer for more details.
function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
$number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
return number_format($number, $decimals, $decPoint, $thousandsSep);
}
I have these value stored in a decimal 10,2 field
1052730
956700
How do i print this using php so that the value is like
$10,527.30
$9,567.00
basically i am trying to avoid the value as
$1,052,730 <--- this i dont want
You can use the
money_format($format, $value)
function in php. The details of the formatting is given here.
Well, assuming that 1052730 is really 10527.30 as alluded to in your question:
$number = 1052730;
$decimals = $number % 100; //30 in this case
$digits = floor($number / 100);
$paddedDecimals = str_pad($digits, 2, '0', STR_PAD_LEFT);
$out = '$' . number_format($digits, 0).'.'.$paddedDecimals;
echo $out; // $10,527.30
There are no floating point calculations used for the decimal part, so there's no need to worry about precision issues (although at this precision it would likely be hard to get a float error in there)...
Just divide by 100:
<?php
echo number_format(1052730/100, 2, '.', ',') . PHP_EOL;
echo number_format(956700/100, 2, '.', ',') . PHP_EOL;
printf ("$%01.2f", ($input / 100));