I'm using simplexml to recover xml from a remote server, and I get values that can look something like this:
1.28586732
-1.2357956
I save these values in a variable but I would like to:
Display each value with no more than 2 decimal places
Have a plus sign precede the value if it is positive
Apply different CSS styles depending on whether the value is positive or negative (for instance display value in red if it is negative)
Thanks!
To display only 2 decimal places you can either use round($num, 2) or sprintf("%.2f", $num), the difference is that sprintf always returns 2 decimal places, i.e. 5 would be 5.00, while round only shows the necessary amount of decimal places. sprintf is also locale-aware.
To have a plus sign precede the value, you would simply do if ($num >= 0) $num = '+'.$num;
And finally to do CSS styling, you should wrap the number in a span and give it a class, i.e. either positive or negative.
To do all of the three, you could have a function like this:
function format_decimal($num)
{
return sprintf(
'<span class="%s">%+.2f</span>',
$num < 0 ? 'negative' : 'positive',
$num
);
}
let:
$s=1.2344545665
if($s>=0)
{
echo "<div class=\"addclass\">+".roundDigits($s,2) . "</div>";
}
else
{
echo "<div class=\"minusclass\">-".roundDigits($s,2) . "</div>";
}
Check out number_format. http://php.net/manual/en/function.number-format.php Then if >= 0 for a positive, <= negative checks.
Related
I want my variable's first decimal to always be rounded up. For example:
9.66 goes to 9.7
9.55 goes to 9.6
9.51 goes to 9.6
9.00000001 goes to 9.1
How do I do this?
Use round() with an optional precision and round type arguments, e.g.:
round($value, 1, PHP_ROUND_HALF_UP)
The optional second argument to round() is the precision argument and it specifies the number of decimal digits to round to. The third optional argument specifies the rounding mode. See the PHP manual for round for details.
Using round() does not always round up, even when using PHP_ROUND_HALF_UP (e.g. 9.00001 is not rounded to 9.1). You could instead try to use multiplication, ceil() and division:
ceil($value * 10.0) / 10.0
Since these are floating-point values, you might not get exact results.
I made couple tests and suggest the following answer with test cases
<?php
echo '9.66 (expected 9.7) => '.myRound(9.66).PHP_EOL;
echo '9.55 (expected 9.6) => '.myRound(9.55).PHP_EOL;
echo '9.51 (expected 9.6) => '.myRound(9.51).PHP_EOL;
echo '9.00000001 (expected 9.1) => '.myRound(9.00000001).PHP_EOL;
echo '9.9 (expected ??) => '.myRound(9.9).PHP_EOL;
echo '9.91 (expected ??) => '.myRound(9.91).PHP_EOL;
function myRound($value)
{
return ceil($value*10)/10;
}
I'm not a php programmer so will have to answer in "steps". The problem you have is the edge case where you have a number with exactly one decimal. (e.g. 9.5)
Here's how you could do it:
Multiply your number by 10.
If that's an integer, then return the original number (that's the edge case), else continue as follows:
Add 0.5
Round that in the normal way to an integer (i.e. "a.5" rounds up).
Divide the result by 10.
For step (2), sniffing around the php documentation reveals a function bool is_int ( mixed $var ) to test for an integer.
You will need a custom ceil() function, your requirements cannot be satisfied by the default function or by the round.
Use this: online test
You can use this technique. Just explode the given number / string, get the number which is next value / digit of the .. after getting this you need to increment that value and check if the value is greater than 9 or nor, if then divide that and add the carry to the first portion of the main number.
$var = '9.96';
$ar = explode(".", $var);
$nxt = substr($ar[1], 0, 1) + 1;
if($nxt > 9){
$tmp = (string) $nxt;
$num = floatval(($ar[0] + $tmp[0]).".".$tmp[1]);
}
else
$num = floatval($ar[0].".".$nxt);
var_dump($num); // float(10)
Hi i need to save a 010 number in $number and if i do like this php will remove the starting 0
$number = 010
And echo of this will return 10 how can i make it not to remove the initial 0
BR
Martin
Use it as a String:
$number = '010';
Use str_pad() function.
echo str_pad('10',3,'0',STR_PAD_LEFT)
http://php.net/manual/en/function.str-pad.php
Do remember that numbers starting with 0 can also be treated as octal number notation by the PHP compiler, hence if you want to work with decimal numbers, simply use:
$num = '010';
This way the number is saved, can be stored in the database and manipulated like any other number. (Thx to the fact that PHP is very loosely typed language.)
Another method to use would be:
Save number as $num = 10;
Later while printing the value you can use sprintf, like:
sprintf("%03d", $i);
This will print your number in 3 digit format, hence 0 will be added automatically.
Another method:
<?php
$num = 10;
$zerofill = 3;
echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);
/* Returns the wanted result of '010' */
?>
You can have a look at the various options available to you and make a decision. Each of the method given above will give you a correct output.
I have some values like:
0.0016662256300037
0.0039870529599284
621.26166045405
-5.99733512656
-223.045
I don't to show if value is zero or equal to zero. I mean I don't want to show these two values 0.0016662256300037 and 0.0039870529599284 currently I am using:
if($pay_balance != '0' ){
echo $pay_balance;
}
Based on the #undone comment
if(intval($pay_balance) !=0){
echo $pay_balance;
}
intval()
If you want to ignore the decimal part of the number, you can convert the value to integer.
if ((int) $pay_balance != 0) {
echo $pay_balance;
}
Try using PHP number_format:
http://php.net/manual/en/function.number-format.php
number_format($pay_balance, 2);
This way numbers with low precision line 0.003 will become 0.00, but if you still want something like 0.1 to be shown it will (instead of just rounding off).
Note that this returns a string, you could cast it to a float from here to do a comparison with 0:
if ((float) number_format($pay_balance, 2) != 0) {
echo $pay_balance;
}
I'm trying to validate a number by it's length. This number has to have 4 digits so it passes the validation. The problem is when this number has 0's to it's left, like 0035.
Right now I'm at this:
echo (strlen ((string) 0025 ));
Which gives a total of 2, but I want this to count the 0's to it's left, so it gives me a total of 4.
Clearly the cast of the integer to string is not working, how can i do this?
You can't do that way, a left zero means the number is octal and not decimal, you can use sprintf() to do that.
Example:
echo strlen(sprintf("%04d", 25));
Live Test:
http://codepad.viper-7.com/VQr7Xz
Comment Answer:
I don't want to add the 0s to the number, i want to detect if the
number has 0s. If the number received is 25, it's not a valid number.
If it is 0025 it is valid. What i want is to validate only numbers
with 4 digits. – Cláudio Ribeiro
Cláudio, numbers have infinite left zeros, although a user has explicitly type 2 or 3 left zeros there are more hidden left zeros, it's a math basic, this is why it's impossible to know how many left zeros the user has typed if you receive an integer variable. If the variable has a constant size and you want to know how many left zeros it has you can do this:
<?php
$int = 25;
echo 4 - strlen($int);
Live test: http://codepad.viper-7.com/fT2jSn
But if you the variable has variable length it must be a string type instead of a numeric type.
An example where the variable received is a string:
<?php
$strs = array("0025","000035","01","2");
foreach($strs as $str)
{
preg_match("/^0+/", $str, $matches);
echo strlen(#$matches[0]);
echo "<br>";
}
Live Test: http://codepad.viper-7.com/BTRTgR
That should work:
$str = "0025";
if( is_numeric($str) && strlen($str) == 4)
{
echo "pass";
}
If it's a number, not a string, the number doesn't have digits. It has a value. You can format that value into a string with 4 digits which is left padded with 0s. But to validate whether a number has 4 digits is nonsense, since the number value has no formatting. The value only becomes "4 digits" when you format it as base 10 number. Until then the value is a value which can be expressed in a multitude of bases and has a different number of "digits" in all of them.
You either want to format the number to a 0-padded 4 digit string, or you want to check whether the value is between 0 and 9999 (or 1000 and 9999 if it has to be exactly "4 digits").
if (0 <= $num && $num <= 9999) {
$numStr = sprintf('%04d', $num);
} else {
trigger_error('Number out of range');
}
How can I separate a number and get the first two digits in PHP?
For example: 1345 -> I want this output=> 13 or 1542 I want 15.
one possibility would be to use substr:
echo substr($mynumber, 0, 2);
EDIT:
please not that, like hakre said, this will break for negative numbers or small numbers with decimal places. his solution is the better one, as he's doing some checks to avoid this.
First of all you need to normalize your number, because not all numbers in PHP consist of digits only. You might be looking for an integer number:
$number = (int) $number;
Problems you can run in here is the range of integer numbers in PHP or rounding issues, see Integers Docs, INF comes to mind as well.
As the number now is an integer, you can use it in string context and extract the first two characters which will be the first two digits if the number is not negative. If the number is negative, the sign needs to be preserved:
$twoDigits = substr($number, 0, $number < 0 ? 3 : 2);
See the Demo.
Shouldn't be too hard? A simple substring should do the trick (you can treat numbers as strings in a loosely typed language like PHP).
See the PHP manual page for the substr() function.
Something like this:
$output = substr($input, 0, 2); //get first two characters (digits)
You can get the string value of your number then get the part you want using
substr.
this should do what you want
$length = 2;
$newstr = substr($string, $lenght);
With strong type-hinting in new version of PHP (> PHP 7.3) you can't use substr on a function if you have integer or float. Yes, you can cast as string but it's not a good solution.
You can divide by some ten factor and recast to int.
$number = 1345;
$mynumber = (int)($number/100);
echo $mynumber;
Display: 13
If you don't want to use substr you can divide your number by 10 until it has 2 digits:
<?php
function foo($i) {
$i = abs((int)$i);
while ($i > 99)
$i = $i / 10;
return $i;
}
will give you first two digits