php round a float if exists and add comma if needed - php

I tried to check similar questions but i didn't get exact same one.So here is what i want
3.45678 to 3.46
3456789 to 3,456,789 //not 3,456,789.00
3456789.45678 to 3,456,789.46
I tried
number_format($num,2) //it adds 00 at the end
round($num,2) //no comma
If its repeated question i apologize for that and please give me the link
thank you!

function convertNumber($number) {
return str_replace('.00', '', number_format($number, $decimals=2, $dec_point='.', $thousands_sep=','));
}

The number formatter class can do that for you, plus it supports any ICU locale.
<?php
$nf = new NumberFormatter("en_US", \NumberFormatter::DECIMAL);
$nf->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$nf->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $nf->format($number, \NumberFormatter::TYPE_DOUBLE);

Haven't tried this
<?php
if (is_float($num)) {
$num=round($num,2);
echo number_format($num, 2);
}
else {
echo number_format($num);
}
?>

Related

Show small numbers without exponential form in PHP and WordPress

Is it possible to show tiny numbers without exponential form?
<?php
$a=4;
$b=799999999999999;
$c=$a/$b;
echo $c;
?>
I use this code in a WordPress page (PHP enabled) and it outputs 5.0E-15 instead of 0,000000000000005
I use default Twenty Sixteen theme without custom functions.
How would you edit the PHP code above in order to show the correct number?
You can use number_format function for this.
<?php
$a=4;
$b=799999999999999;
$c=$a/$b;
$d = number_format($c, 15, ',', '');
echo $d;
?>
Outputs: 0,000000000000005
But as you stated, you need a more dynamic solution as the decimal place isn't fixed. So here's my proposed solution.
Long version:
<?php
$a=4;
$b=799999999999999;
$c=$a/$b;
$e = 0; //this is our output variable
if((strpos($c, 'E'))){ //does the result contain an exponent ?
$d = explode("-",$c); //blow up the string and find what the decimal place is too
$e = number_format($c, $d[1], ',', ''); //format with the decimal place
}else{
$e = $c; //Number didn't contain an exponent, return the number
}
echo $e;
?>
and here's the previous code shortened down a bit:
<?php
$a=4;
$b=799999999999999;
$c=$a/$b;
$d = (strpos($c,'E')) ? number_format($c,explode("-",$c)[1],',','') : $c;
echo $d;
?>
( I deleted my answer and reposted as I'm not sure if you got the alert that I amended my answer)

trouble with calculating percentage using PHP

I wanted to calculate the percentage using PHP. I tried the code given below but its gives me the return value in float. i don't know much in PHP so please fix this code.
current OUTPUT
66.666666666667%
Expected OUTPUT
66.66%
<?php
$up=4;
$down:2;
echo (($ups/($ups+$downs))*100).'%';
?>
Use number_format() to specify your decimals and separator.
<?php
$up=4;
$down:2;
$num = (($ups/($ups+$downs))*100).'%';
$formatted_num = number_format($num, 2, '.', '');
echo $formatted_num;
?>
You can do like this :
echo round(66.666666666667, 2); >> 66.66

Change from string to variable

Hi Guys , just need a tiny help here . the green numbers on the right are strings . how do I change them to numbers ? Additionally I also need them to be 2 decimal place. What function do I use?? I tried the method below but the output was 0. Answers all welcome.
$profitText = $profitText*1;
$profitText = (float)$profitText;
round($profitText,2);
number_format($profitText, 2);
EDITED
Okay guys the deriving of this variable is really complex. every step has its functional purpose but heres the derivation. After the last profitText at the bottom, I realised this is now a string. why is that so? and how do I fix it?
$offeropen=$row['offerprice'];//1.3334
$pips=$offerpricepl-$offeropen;//difference btw prices , eg. 0.0023
$closedb=$offerpricepl;// nothing
$pips1=round($pips, 6);// round to 6 decimal points
$pips2 = str_replace('.', '', $pips1);// remove decimal
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);// methodology for adjusting figures and negative values back
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');// for triming 0 on the left
}
$pips3=$pips2/$minipipskiller;// methodology
$ticksize= "0.0001";// FOR PROFIT AND LOSS
$lot1 = "100000";
$sizecalc=$row['size'] * $lot1;
if ($row['type']=="buy")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
if ($row['type']=="sell")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
$zero= '0';
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$profitText=ltrim($profitText,'0');
Here's your problem:
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
You're trying to turn $profitText into a number. It's actually a string of HTML, and PHP can't manage to work out what it's supposed to do with it, so when you cast it to a number, it's returning 0.
Solution:
Use $profitandloss instead
this will do both requested points together:
$floatProfitVar = number_format($profit, 2, '.');
I think you need
floatval(mixed var)
http://www.php.net/manual/en/function.floatval.php
$profit = round(floatval(trim($profitText)), 2);
Proof: http://codepad.org/jFTqhUIk
The function you're looking for is sprintf or printf and has been designed for exactly that job:
printf('%.2F', '1.8'); # prints "1.80"
Demo: https://eval.in/44078
You can use string input for the float number parameter (F = float, locale independent) as well as integer or float input. PHP is loosely typed.
Use sprintf if you want to get back a string, printf prints directly.
$value = intval(floatval($profitText)*100)/100.0
I don't think this $profitText = $profitText*1; would work unless you first do $profitText = (float)$profitText;. Remember that you have to convert the string first before you can do any manipulation.
floatval(mixed $var) can also be used instead of typecasting but typecasting should work fine

How can I check if number has one , or two decimals?

I would like to know how I can check if a number has one or two decimals, and if it only has one decimal , like 12,9 for example, then echo the number with an additional 0, so it looks like 12,90.
<?php
$number = '12,9';
if $number //has 2 decimals // {
echo $number; }
else {
echo $number.'0';
}
endif;
?>
I have no clue how to do that properly, any help would be really appreciated! Thanks
If your input is a . (dot) separated decimal, you can just use number_format():
number_format('12.9', 2);
Alternatively, you can use the NumberFormatter class if you need to support multiple locales or numbers with commas for decimal separators. Such as:
$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format($formatter->parse('12,9'));
Note: The use of NumberFormatter requires the intl extension. It can be added on debian based systems with a simple sudo apt-get install php5-intl.
If you're sure that the number is always formatted like you've posted, than you could do:
number_format(str_replace(',', '.', '12,9'), 2, ',', '.');
what you need is the number_format function
http://www.php.net/manual/en/function.number-format.php
Since PHP is not strictly typed, you could so something like this:
$parts = explode(",", $number);
$num_decimals = strlen($parts[1]);
if ($num_decimals == 2) //has 2 decimals // {
echo $number;
} else {
echo $number.'0';
}

PHP Currency formatting trailing zeros

Is it possible to have PHP format currency values, for example: $200 will output as: $200 (without decimals) but with a number like $200.50 it will correctly output $200.50 instead of $200.5?
Thanks! :)
$num_decimals = (intval($amt) == $amt) ? 0 :2;
print ("$".number_format($amt,$num_decimals);
If you don't mind handling the currency on your own, you can simply use the following on the number, to get the correct output.
This solution will always output trailing zeros (xx.x0 or xx.00 depending on the provided number)
$number = 1234
sprintf("%0.2f",$number);
// 1234.00
How about a custom function to handle the situation accordingly:
function my_number_format($number) {
if(strpos($number, '.')) {
return number_format($number, 2);
} else {
return $number;
}
}
you can use number_format to do this.
Example:
$Amount = 200.00;
echo "$" . number_format($Amount); //$200
There are a couple of ways. Probably the most universally supported and recommended method is sprintf.
sprintf("%01.2f", "200.5"); //200.50
sprintf("%01.2f", "10"); //10.00
number_format is good as well, and has all sorts of options, and it will add thousands separators and such if requested to do so.
There's also a money_format function, but it is unsupported on Windows servers.

Categories