I have to print a numeric value which is less than 10 in the following format:
for 0 I want to print it 00
for 1 I want to print it 01
for 2 I want to print it 02
Are there any php library functions which will format numbers in this way?
Use printf or sprintf:
$i = 1;
printf('%02d', $i);
See it in action.
The sprintf page also documents the syntax for formatting specifiers (%02d), so you can also see what other options are available.
printf('%02u', $number)
http://php.net/sprintf
Use str_pad function.
str_pad($number_str,2,'0',STR_PAD_LEFT)
PHP Manual - str-pad
You can check if the value is less than ten and concatenate using the dot operator '.', i.e.
if($i < 10 && $i >0) print '0'.$i;
else print $i;
Related
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.
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
Say I have 1.234 I want to get the .234
I tried echo 1.234%1 //I get 0
I am rusty, what is the correct way?
(The tags says PHP as this might be an issue only with PHP, but I really am looking for the general solution).
php's % modulo operator converts its arguments to integers. To get a floating-point modulus, use fmod:
echo fmod(1.234, 1);
You can remove the whole number from the number itself. in php its:
$num = 1.234;
echo $num - floor($num);
Subtract the integer portion of $x ((int)$x) from $x:
$x = 1.234;
$d = $x - (int)$x;
// $d now equals 0.234
echo $d;
Example
Just substract integer part 1.234 - (int)1.234
Try this:
echo 1.234 - intval(1.234);
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.
Hay how can I convert
01 to 1
02 to 2
all the way to 9?
Thanks
I assume the input is a string?
$str = "01";
$anInt = intval($str);
You may think that the leading 0 would mean this is interpreted as octal, as in many other languages/APIs. However the second argument to intval is a base. The default value for this is 10. This means 09->9. See the first comment at the intval page, which states that the base deduction you might expect only happens if you pass 0 in as the base.
$x="01";
$x=+$x;
$x="02";
$x=+$x;
...
or
$x=+"01";
should work for both int, and string
Do (int)$str; instead. It's up to 4x faster than intval().
$str = "05";
$last = $str[1];
$i = substr($input, 1, 1);
If you want to use the generic regular expression solution: 's/[0]([0-9])/\1/' (add in anchors as appropriate)
$str='05';
if(strpos($str,'0')==0 && strpos($str,'0') != false ){
$new = intval(substr($str,1));
}
you can use the predefined php function .
intval()
For Ex:
$convert = intval(01);
echo $convert ;
It will print 1(one);