Comparing number sizes for numbers that start with 0? - php

I am trying to compare numbers against each other in terms of size and pick the closest (largest) value.
For example i have the array of numbers: 0541, 0555, 0789.
And a number: 0547.
In this case 0555 would be my desired number.
My code works for all numbers not starting with a 0, but with the above example it fails.
Any ideas?
EDIT: Should have made it clear, not all numbers start with a 0, and the number to be compared is the time so is it still possible to remove the zero from that?

If you have a number that starts with a 0 it will be compared as a string. Turn the numbers into integers before comparing using intval (http://php.net/manual/en/function.intval.php)

Related

PHP (int) generates wrong number

I am working on a PHP-script that handles monetairy amounts, and therefore needs to be exact with 2 decimals. To do this, I convert the user-input to a number by multiplying it with 100, and then casting it to int. This works fine, untill I recently discovered a number that increases by 1 when cast to int.
the malfunctioning code:
$number = (int)(str_replace(',','.',$_POST["input"])*100);
The number that gives problems is 2509,22 (I live in the Netherlands, so we use comma's for decimals, hence the str_replace in the above line of code).
This value creates the integer $number 250921, which is obviously 1 too low.
I know that int has limits, but this number is well within those limits as far as I'm aware...
When you multiply the string by 100 you get a float and its representation is not always what you expect, in this case 250921.99999999997. See it with:
echo serialize(str_replace(',','.','2509,22')*100);
Then you cast to an integer which trucates the fraction to get 250921. See Is floating point math broken?.
The solution would be to remove the comma and use as is and optionally cast to an integer:
$number = (int)str_replace(',', '', '2509,22');
For the issue of users entering too many fractional numbers, you should either use two inputs, one for whole number and one for fraction and/or restrict/validate that the inputs are correctly formatted. However, you can format the number first:
echo $number = (number_format(str_replace(',', '.', '2509,22'), 2, '.', '')*100);
You can use regex to match the int and zero - two decimals.
This will not do any conversions and nothing is multiplied or casted.
It will be treated as a string and nothing changes but the number of decimals.
$input = "2509,2222222";
// Regex number comma number (zero - two)
Preg_match("/(\d+),*(\d{0,2})/", $input, $m);
Unset($m[0]); // remove full match
Echo implode("", $m); // implode parts
https://3v4l.org/MjcYV

How to find last 8 digit of number 0000548795846

I want to find last 8 digit of number 0000548795846 in php.
Its done fine when I use string but I have some problem with Integer starts with zero.
Try with -
substr(" 0000548795846", -1, 8);
In your example what is happening is that, PHP by default considers the number starting with 0 (zero) as octal number i.e base 8, and you are expecting it as decimal.
When PHP comes across any number starting with zero it converts it into decimal equivalent of the actual number for ex. 0000548795846 gets converted into 44 decimal, so there is no length >= 8 present.
So, Solution is to convert the number in string format. Then use substr() with appropriate arguments, as suggsted by "sgt"

Trim zeros to the right of a decimal place and decimal point often

I have been handling long numbers in PHP. Like the following examples.
12.020000
12.000000
To get rid of trailing zeros and the decimal point I have been using the following inside a function.
return rtrim(rtrim($str, "0"),".");
So the above turns out like.
12.02
12
It was a bit short sighted as when 1000 gets entered it gets turned into 1.
Can someone please help me with the code to remove trailing zeros after the decimal point only?
Bonus points if the code removes the decimal place but I can always feed it into rtim($str,".").
EDIT: To be clear, I am stripping the decimal place and zeros only when displaying to the screen. Also casting to float is not an option as I also handle numbers like 0.00000001 which come out like 1.0e-9 sort of thing.
Why are you using string to hold numbers? Cast it to float and it'll solve your problem.
$string = '12.020000';
$number = (float) $string; // will be 12.02
Then, if you want to use it as string (but why?)
$string = (string) $number;
The thing that perplexes me about your question is that extra zeros won't be included in a number variable without intentionally adding them with number_format. (This may be why someone down-voted it).
Normally you don't want to use string functions (meant for text) on variables that hold numbers. If you want to round off a number, use a function like round.
http://php.net/manual/en/function.round.php
There's also number_format, which can format numbers by adding zero padding: (it doesn't actuall round, just trims off excess numbers).
http://php.net/manual/en/function.number-format.php
Since your zeros are appearing, it's likely that you simply need to multiple the variable by 1, which will essentially convert a string to a number.
Good luck!

How to match those numbers?

I have an array of numbers, for example:
10001234
10002345
Now I have a number, which should be matched against all of those numbers inside the array. The number could either be 10001234 (which would be easy to match), but it could also be 100001234 (4 zeros instead of 3) or 101234 (one zero instead of 3) for example. Any combination could be possible. The only fixed part is the 1234 at the end.
I cant get the last 4 chars, because it can also be 3 or 5 or 6 ..., like 1000123456.
Whats a good way to match that? Maybe its easy and I dont see the wood for the trees :D.
Thanks!
if always the first number is one you can use this
$Num=1000436346;
echo(int)ltrim($Num."","1");
output:
436346
$number % 10000
Will return the remainder of dividing a number by 10000. Meaning, the last four digits.
The question doesn't make the criteria for the match very clear. However, I'll give it a go.
First, my assumptions:
The number always starts with a 1 followed by an unknown number of 0s.
After that, we have a sequence of digits which could be anything (but presumably not starting with zero?), which you want to extract from the string?
Given the above, we can formulate an expression fairly easily:
$input='10002345';
if(preg_match('/10+(\d+)/',$input,$matches)) {
$output = $matches[1];
}
$output now contains the second part of the number -- ie 2345.
If you need to match more than just a leading 1, you can replace that in the expression with \d to match any digit. And add a plus sign after it to allow more than one digit here (although we're still relying on there being at least one zero between the first part of the number and the second).
$input='10002345';
if(preg_match('/\d+0+(\d+)/',$input,$matches)) {
$output = $matches[1];
}

Turn zero filled numbers into whole numbers

I have a selection of nubmers which are prefixed with zeros to give them a set length.
0001,0230,1000,0007,0300
How could I make these whole number? So that the resulting numbers are
1,230,1000,7,300
I was using sprintf("%04d", $input); to generate the numbers, is there a reverse of this?
Thanks
If you feel safe that you have numbers and not another kind of string, you can just cast to integer:
(int) $num;
Demo: http://codepad.org/VQrA50fK
Just be aware that a non-integer (like a string with letters) will cast to 0.
Check out the intval function. Just pass them in and they'll be converted to ints. You can then append them to a sting to make them strings again.

Categories