23

I tried (int) "4209531264" and intval("4209531264") but sadly all I get is 2147483647 (I realize this is because of 32 bit architecture or some php dependencies or something).

I came up with "4209531264" + 0 which returns the correct result but it is surprising to see it working since it is beyond maxint.

but the real question: is this the "right way" of converting string to long?

edit:

(float) that is.

thanks for the comments! eye opening!

5
  • 8
    (float) "your string" Commented Jun 2, 2014 at 19:52
  • 1
    Are you on a 32-bit platform? You'll need to use float instead of int, since that number is too large for a 32-bit signed integer. Commented Jun 2, 2014 at 19:53
  • The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. php.net/manual/en/function.intval.php Commented Jun 2, 2014 at 19:53
  • 2147483647 is the maximum integer value on 32bit systems. Commented Jun 2, 2014 at 19:53
  • 1
    Related var_dump(PHP_INT_MAX); Commented Jun 2, 2014 at 19:53

1 Answer 1

20

As long as you are not very particular about what exactly kind of value you end up with, "number" + 0 is probably the best way of converting your input because it converts to the "natural" numeric data type.

The result will be an integer if the input has no decimal part and fits (see PHP_INT_MAX) or a float if it does not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.