I need to check if a number is greater than 50,000,000, but I want to avoid the typical:
if (numero > 50000000) {
//....
}
Is there a way to check it with "regex", or another way?
I need to check if a number is greater than 50,000,000, but I want to avoid the typical:
if (numero > 50000000) {
//....
}
Is there a way to check it with "regex", or another way?
To write it shorter:
That's it
5 * 10^7
(or " a 5 followed by 7 zeros ") .
And, no, no, no, no, no, no!!! Don't use regex for something as simple as this. It's going to turn a trivial statement into an elephant trying to eat a peanut through the keyhole... For the curious, the regex would be
/^0*(?:(?:[6-9]|[1-5]\d|5(?=0*[1-9])))\d{7}/
, but don't use it, much less say I wrote it.As a contribution to Mariano 's and Larry U 's answers , I add a possible solution, obviously not so elegant.
Using bit shifts , I generate the following numbers:
Which when added together give
50000000
. It can be used to compare and determine if the number is less or greater.Update
I have made a comparison regarding the speed with which these instructions could be executed, in relation to @Ruben's comment:
Conclusion: Mariano's response is more efficient, with respect to execution speed, as can be seen in these examples.
The comparison can be made in binary, or in any other base.
Using the method
toString
, passing a base number as an argument, that is,toString(base)
, we can compare the number in base 36, which is the maximum allowed by the method.In this case, if the string has a length equal to that of the string
tro8w
, which is 50 million in base 36, and also, if it is greater alphabetically than that string, or if it has a greater length than that of the string, we have to returntrue
_I think that using regex, a number greater than 50000000 can be represented as follows:
If the figure has 8 digits, the first of them cannot be equal to 50000000
We add the rest of the 8-digit figures greater than 50000000
If the figure has more than 8 digits, the first of them must be greater than or equal to 1 (avoid validating 9 zeros or more)
Any of these figures can have infinite zeros
0*
at the beginning of them.Combining these expressions we get:
^0*(?:5(?!0{7})|[6-9]|[1-9]\d)\d{7,}$
^
and$
are to guarantee that the variable is a number(?: )
Group elements together without saving any references or links for future use.(?! )
It helps me detect a pattern after a certain expression and discard it, in this case 7 zeros after a 5.For the not so " scientific ":
And then,
Or even,