tags:

views:

119

answers:

4

How to get the first two numbers in an integral?

For example: get 12 of the 123456 in PHP or JavaScript?

+7  A: 

JavaScript:

(123456).toString().substr(0,2);

PHP:

substr(123456, 0, 2);
Delan Azabani
It should work even without adding `'' . ` :)
Sarfraz
Really? I was just typoecasting to make sure. I'll simplify it, thanks very much! ;)
Delan Azabani
Doesn't work for large numbers, though. 1234500000000000000000 becomes '.1' instead of '12'.
Guffa
@Guffa: That's because calling `.toString()` on large numbers gives the scientific notation (X.Ye+Z)
Delan Azabani
@Delan: Thanks for the clarification, perhaps I should have included the reason in my comment but it seemed so obvious at the time...
Guffa
+2  A: 
$result = substr("123456", 0, 2);
sea_1987
+10  A: 

PHP:

$num = 123456;
echo substr($num, 0, 2);

JavaScript:

alert((123456).toString().substr(0, 2));
Sarfraz
Doesn't work for large numbers, though. 1234500000000000000000 becomes '.1' instead of '12'.
Guffa
if you wrap it in qoutes eg `'1234500000000000000000'`, it sould work and then you can type cast later once you have got the desired part of the number. Example: `$num = '1234500000000000000000';$output = substr($num, 0, 2);echo (int) $output;`
Sarfraz
@Sarfraz: Then it's not a number, as requested in the question...
Guffa
@Guffa: Ofcourse not but as i said once you get the required digits, you can type cast them again to convert them to number. And as Delan Azabani said, that is because it converts to scientific notation. Thanks
Sarfraz
@Sarfraz: You are missing the point. If the input is a variable containing a numeric value, you can't just put apostrophes around it. If you could change the input that way, you could just as easily remove all but the first two characters, and this entire question would be pointless.
Guffa
@Guffa: Ok got your point, thanks for that.
Sarfraz
+1  A: 

Numerically in Javascript:

while (number >= 100) number = Math.floor(number / 10);
Guffa
This will produce a float.
Alsciende
@Alsciende: Yes, you are right. I changed it to remove the fractions.
Guffa