I am playing with Twitter API. Some numbers (like Twitter ID) is really large such as 199693823725682700.
I've got this number as string format, and now I need to change it to just normal readable number, not like 1000xE09, because I need to substract -1 from that string-casted number. Then, I also need to send the number as string.
In sum, in PHP, how can I change the string a number, eg, "199693823725682700" to another string "199693823725682699" (original number -1)?
Thanks a lot!
If BCMath is not available (it would be the preferable option if it is available) this function will decrement an arbitrarily sized integer stored as a string. There is no handling for floats or interpolation of scientific notation, it will only work with a string of decimal digits with an optional sign.
function decrement_string ($str) {
// 1 and 0 are special cases with this method
if ($str == 1 || $str == 0) return (string) ($str - 1);
// Determine if number is negative
$negative = $str[0] == '-';
// Strip sign and leading zeros
$str = ltrim($str, '0-+');
// Loop characters backwards
for ($i = strlen($str) - 1; $i >= 0; $i--) {
if ($negative) { // Handle negative numbers
if ($str[$i] < 9) {
$str[$i] = $str[$i] + 1;
break;
} else {
$str[$i] = 0;
}
} else { // Handle positive numbers
if ($str[$i]) {
$str[$i] = $str[$i] - 1;
break;
} else {
$str[$i] = 9;
}
}
}
return ($negative ? '-' : '').ltrim($str, '0');
}
Sure.
BC Math module
Function http://de.php.net/manual/en/function.bcsub.php
Apparently for now only way to deal with large integers in php is to use the bcmath
extension. 64-bit integers are planed in PHP6.
You should try GMP with PHP,
here is the manual .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.