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');
}
Related
I am looking for a solution for a smart number formatting in PHP.
For example we have 2 numbers below and we need 4 digits after decimal:
1.12345678
0.00002345678
Using normal number formatting, here are the results:
1.1234 // Looking good
0.0000 // No good
Can we make it keep going until there are 4 non-zero digits? If it can return 0.00002345, perfect!!!
Many thanks!!!
Might be overkill and the pattern could be optimized, but for fun; get optional 0s AND 4 NOT 0s after the .:
preg_match('/\d+\.([0]+)?[^0]{4}/', $num, $match);
echo $match[0];
To round it we can get 5 digits after the 0s and then format it to the length of that -1 (which will round):
preg_match('/\d+\.([0]+?[^0]{5})/', $num, $match);
echo number_format($match[0], strlen($match[1])-1);
For $num = '1234.000023456777'; the result will be 1,234.00002346 and the $matches will contain:
Array
(
[0] => 1234.000023456
[1] => 000023456
)
So this is the code I made to slove this:
$num = 0.00002345678;
$num_as_string = number_format($num,PHP_FLOAT_DIG,'.','');
$zeros = strspn($num_as_string, "0", strpos($num_as_string, ".")+1);
echo number_format($num, (4+$zeros), '.', '');
It converts the float number to a string, checks how many zeros exist after the decimal point and then does a number format with the extra zeros accounted for.
Note that it may break if your float is too big, you can change PHP_FLOAT_DIG to a number larger that may fix that.
Number format adds the commas I want but removes the decimals.
echo number_format("1000000.25");
This returns 1,000,000
I want it to return 1,000,000.25
I need both the commas and the decimals, without any number rounding. All my values are decimals. They vary in length.
Do I have to use something other than number format?
In case what you meant by they vary in length is related to the decimal part, take a look at this code:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
Some tests
Output for 1000000.255555:
1,000,000.255555
Output for 1000000.25:
1,000,000.25
Output for 1000000:
1,000,000
It counts how many chars there are after the . and uses that as argument in the number_format function;
Otherwise just use a constant number instead of the function call.
And some reference...
From the manual -> number_format():
string number_format ( float $number [, int $decimals = 0 ] )
And you can see in the description that
number
The number being formatted.
decimals
Sets the number of decimal points.
And a bit more:
[...]If two parameters are given, number will be formatted with decimals
decimals with a dot (".") in front, and a comma (",") between every
group of thousands.
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
Explanation:
Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs. This Stack overflow answer tells you how to get the number of decimal places of your provided string
The docs for number_format() indicate the second parameter is used to specify decimal:
echo number_format('1000000.25', 2);
Ref: http://php.net/manual/en/function.number-format.php
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
I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.
Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.
This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.
$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
if (substr($s, -1) == '0')
$s = substr($s, 0, -1);
}
print "Number = $s";
Use sprintf() to format a number to a certain number of decimal places:
$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);
I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.
But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:
$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
chop off last character of $mystring;
}
Check the number format function:
<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>
http://php.net/manual/en/function.number-format.php
Using preg_match just get the zero ending with and then rtim it
<?php
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
echo rtrim($nn,$number[0]);
}
Hope it will help you.
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.