String number to integer not working PHP - php

I am trying to get a string number to an integer but it's not working as expected here is the code with the problem:
$usage['msisdn'] = "46720000000";
$usage['msisdn'] = (int)$usage['msisdn'];
echo $usage['msisdn'];
It echoes 2147483647 as integer but I want to get 46720000000 as integer.
What's wrong?
By the way I'm parsing the data using json_encode();
UPDATE: Nevermind I've got it to work with intval()

That's because the maximum value of int32 is 2,147,483,647. Your phone number exceeds this value.
You can find the maximum value of int on your server using:
echo PHP_INT_MAX;
I think that storing a phone number as integer is a bad practice and it may affect you later. Why? Because the phone number may start with:
IDD: 00 or +
NDD: 0
Also, you may want to format the phone number at some point, storing it as string making this part much easier.
Christmas bonus :) libphonenumber-for-php

Your code isn't working because the conversion string to int as a maximum value based on your system as quoted in the documentation :
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. The maximum signed integer value for 64 bit systems is 9223372036854775807.
Source : http://php.net/manual/en/function.intval.php
Since you cannot modify the max_int value easily, you could try to use a conversion to float instead.
$usage['msisdn'] = floatval($usage['msisdn']);

Related

Numeric problems in PHP (max possible value for a 64 unsigned integer)

This is the example code I'm running.
<?php
//$maxval = (2**64)-1;
$maxval = (2**64);
$maxval = $maxval-10000;
echo number_format($maxval,0,".","") . "\n";
echo "18446744073709551615\n";
?>
The code if for checking a number that will come as a string and I need to make sure it is an unsigned 64 bit integer. So once I check that the string is composed ONLY of numbers I need to make sure that the range is correct.
But I'm getting some weird behaviour.
This line (2**64)-1; printed 18446744073709551616. It seemed it ignored the -1. So I started changing -1 to -10, -100, -1000 and they all printed the same value. It only changed when I changed it to -10000 and this is what it printed:
18446744073709541376
18446744073709551615
But to my understanding the first line should be
18446744073709541615
So what am I doing wrong?
Integer in PHP is a signed integer. There are constants PHP_INT_MIN and PHP_INT_MAX for the smallest and largest value.
//64 Bit PHP Version !
var_dump(PHP_INT_MAX); //int(9223372036854775807) = 2**63-1
If the values ​​are greater than the integer range, PHP automatically converts to float. Float, however, is far less precise than 63 bits. This is where the inaccuracies come from.
The bcmath functions can be used to calculate with almost any precision. This code is for checking a number that will come as a string and is an unsigned 64 bit integer.
$val = "18446744073709551614";
$maxUnsign64Bit ="18446744073709551615";
if(ctype_digit($val) AND bccomp($val,$maxUnsign64Bit) !== 1){
echo 'is a 64 Bit number';
};

Totally wrong result of intval and(int) of double number

I've got this problem on Windows 10 with both php 7 and 7.1 and also on raspbian with PHP 7.0.33
When I try to cast a large double (a miliseconds timestamp) to int I get a totally wrong result. Example:
$a = 1512298800000.0;
echo intval($a);
The output is: 470311808
Any suggestion on how to troubleshoot this?
Based on intval() Manual, it cleary states:
Return Values
The integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.
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. The maximum signed integer value for 64 bit systems is 9223372036854775807.
Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.
And
Notes
Note:The base parameter has no effect unless the var parameter is a string.
So basically it seems you are using 32-bit system and value got overflowed from the range of integer.

JavaScript VS PHP: The same calculation returns different result

I'm trying to do some simple math (?) in JavaScript:
( 1023 * 2 ) + 76561197960265728;
I already did the same calculation in PHP, but the results are different:
JavaScript: 76561197960267780
PHP: 76561197960267774 (the right result)
I then tried the following:
http://jsfiddle.net/YxBa4/
Is there a "limit" in JavaScript for high numbers in calculations?
//edit:
Thanks for your answers, I now use the BigNumber one.
My full working code now:
on JSFiddle
In Javascript, numbers are 64 bit floating point values. The largest integer (magnitude) is 253, or Math.pow(2,53), or 9007199254740992. taken from: http://notepad2.blogspot.ca/2012/04/maximum-integer-in-javascript.html
You are 1351079458714420 over the limit.
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5. taken from http://php.net/manual/en/language.types.integer.php
So basically PHP allows you more capacity for Integer values according to the PHP configuration.
The value 76561197960265730 id greater than the maximum allowed number size in javascript. Note that there are no real integers in Javascript just the Number type which is always a 64bit floating point value and platform independent. But the largest possible integer value is just 2^53 because 11 bits are at least reserved for the numbers after the comma and the signage bit.
In your example you can see this by simply doing:
alert(76561197960265728);
What will give you already an error, even without any calculations. (output: '76561197960265730')
In php the maximum integer value depends on your system. If you are on a 64 bit system, the MAX integer value is 2^64 what is greater than (2 * 1023) + 76561197960265728. That'swhy the calculation succeeded in PHP - on a 64 bit system
In PHP you can detect the maximum integer size on your system by reading the constant PHP_INT_MAX and `
You could use the bcmath extension for PHP and the JS conversion of it to get consistant results across the 2 languages:
bcadd('76561197960267774', '76561197960267774');
// 153122395920535548
http://jsfiddle.net/zELmm/
http://phpjs.org/functions/bcadd/
http://php.net/manual/en/function.bcadd.php
Update:-
BigInt was added as a native features of JavaScript.
But still there are some precision error on round off, A workaround Comparison
For example here full code for comparing BigInt with Number in JavaScript
As per Initial Problem Here :-
PHP: 76561197960267774 (the right result)
var num = BigInt( 1023 * 2 ) + 76561197960265728n;
console.log(num.toString());
/*
num.toString() removes n at the end of digit.
Output: 76561197960267774
*/
Where bigint, created by appending n to the end of an integer literal or by calling the BigInt() constructor.
So after using BigInt:-
JavaScript: 76561197960267774 (the right result)

Converting type numeric value from string to integer without changing its value

I am reading a csv file and my code is reading the numeric value as a string.
But i need the value as integer.
e.g. string '5782492380' as int '5782492380'
Is there any best way to change the type of value from string to int in php code?
I have tried as
(int) 5782492380
but it is changing the original value to 2147483647.
Try with float, as int has a limit under your value:
$v = (float) 5782492380;
In PHP: integers you can find the comment:
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18
So the integer range value is (-2147483648, 2147483647).
Value 5782492380 does not fit into integer type. Integer values should be in range -2147483648 .. 2147483647 inclusive. To store values that are outside this range, you may use floating point numbers or GMP numbers.
$v = intval( $your_string)
range is up to 232

Convert a big integer to a full string in PHP

I've been searching for a while now, but what I can find is not what I search for. I need to convert an integer value, that may be very huge, to a string. Sounds easy: "$var"? No, because this can lead to the E+ representation of the number.
<?php
$var = 10000000000000000000000000;
echo $var."\n";
echo "'$var'\n";
echo (string) $var."\n";
echo strval($var);
?>
1.0E+25
'1.0E+25'
1.0E+25
1.0E+25
How can I make the output be 10000000000000000000000000 instead?
This is not stored as an integer by PHP, but a float, this is why you end up with 1.0E+25 instead of 10000000000000000000000000.
It's sadly not possible to use that as an integer value in PHP, as PHP cannot save an integer of that size. If this comes from database then it will be a string and you can do with it whatever you want. If you store it elsewhere then store it as a string.
Your alternative is to store it as a float and take that into account at all times, though that requires additional conversions and handling in places.
It's also been suggested to use GNU Multiple Precision, but that's not enabled in PHP by default.
$int=gmp_init("10000000000000000000000000");
$string=gmp_strval($int);
echo $string;
UPDATE:
Found the next post:
// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015
// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
Use printf or sprintf.
I'm facing this problem when getting facebook id and find it in MySQL.
And after half hour, i found this work perfectly!
Insert this line to your php script:
ini_set('precision',30);
From: https://forums.phpfreaks.com/topic/125907-solved-convert-big-number-to-string/#entry651084
The integer number you like to express:
$var = 10000000000000000000000000;
is not available on your system. It's too large and therefore PHP converts it into a float which will change the number (32 bit system example):
10000000000000000905969664
Common limits are:
yours : 10 000 000 000 000 000 000 000 000
32 bit: 2 147 483 648
64 bit: 9 223 372 036 854 775 808
The change of the value is called floating point precision, the PHP manual about integers will tell you about the integer limit and the floats page about floating point precision (see the big red warning). Depending on which system you are, you can compile PHP with the ranges your application needs or you must use another datatype, for example with the gmp library which is able to pick strings as integer numbers and handle them.
The following example shows just output, but you can do multiplications etc.:
$r = gmp_init('10000000000000000000000000');
echo gmp_strval($r);
Hope this is helpful.

Categories