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";
Related
I am trying to get number value with plus and minus
<?php
$num1= '-12.20000';
$num2= '+18.20000';
echo rtrim(str_replace('.00', '', number_format($num1, 2));
echo rtrim(str_replace('.00', '', number_format($num2, 2));
?>
Need output like
-12.2
+18.2
I can't see exactly what you need. There are not enough examples and your description of the task is not sufficient.
The number is formatted with a sign and 2 decimal places. If the last digit is a 0, it is removed with preg_replace().
$data = ['-12.20000','+18.20000', 234.0, 2.1234];
foreach($data as $value){
$formatVal = sprintf("%+0.2f",$value);
$formatVal = preg_replace('~(\.\d)0$~','$1',$formatVal);
echo $value.' -> '.$formatVal."<br>\n";
}
Output:
-12.20000 -> -12.2
+18.20000 -> +18.2
234 -> +234.0
2.1234 -> +2.12
If the result is only ever required with one decimal place, you can use
$formatVal = sprintf("%+0.1f",$value);
without the preg_replace.
In python, you could do it like this:
def returnWithSign(str):
n = float(str)
if n>0:
return '+{}'.format(n)
return n
Instead of using difficult functions in PHP just use the native stuff PHP brings with it. One fantastic thing of that stuff is the NumberFormatter class.
$formatter = new NumberFormatter( 'en_GB', NumberFormatter::DECIMAL );
$formatter->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$num1= '-12.20000';
$num2= '+18.20000';
echo $formatter->format($num1) . PHP_EOL;
echo $formatter->format($num2) . PHP_EOL;
Exactly does what you want.
Output: https://3v4l.org/UQX3Y
I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.
So how can I do this like the following conversion
11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
This might help, You can use sprintf given by PHP.
You can use float casting
echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;
and you have to check number of digits after decimal point and than get value like below :
$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
echo number_format($val,2);
}
You may use the round() function for this.
i-e round(number,precision,mode);
Example:
echo(round(11.2200,2));
Output
11.22
Thanks
Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:
$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
// CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
$x = (float)$x
// EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
$pieces = explode('.',$x);
// IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
if(isset($pieces[1]))
{
// IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
if(strlen($pieces[1]) == 1)
{
$x .= '0';
}
}
// IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
else
{
$x .= '.00';
}
}
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);?>
I have a doubt with how to use the number_format and round function together, this because I have an script to import all my supplier's products, but I need round the prices, for example:
Supplier's price: $1854.81
The price rounded: $1854.99 (This is the format that I want)
The price that my script print: $1,854.90
I tryed 3 PHP variant to do this:
Variant #1:
$preciosinr = 1854.81;
echo number_format(round($preciosinr*4)/4,2); //Print 1,854.90
Variant #2
$preciosinr = 1854.81;
$pos = 3 - floor(log10($preciosinr));
echo number_format(round($preciosinr,$pos)-0.10,2); //Print 1,854.75
Variant #3
$preciosinr = 1854.81;
number_format($preciosinr,2);
number_format(round($preciosinr,1),2);
number_format(round($preciosinr,0),2);
echo number_format(round($preciosinr,0)-0.01,2); //Print 1,854.99
As you can see all the variants prints the price with "," and I need the price without this because my system detect the price incorrectly.
I read in php.net that I need use the following sintaxis but I don't know how can integrate with my code.
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
Can you help me?
$price=number_format(round($preciosinr,0)-0.01,2,'.','');
echo $price;
This should work
I found it strange that the answer that was accepted is actually wrong.
Example case:
// The input we want to check
$stringNumber = '7616.95';
// As suggested by accepted answer
$formatted = number_format(round($stringNumber,0)-0.01,2,'.','' );
echo $formatted; // Outputs: 7616.99
A better solution is found here:
https://stackoverflow.com/a/7459107
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'];