Here's a way to parse a decimal (eg 3.25) into an integer and exponent:
<?
if (preg_match("/^[0-9]+\.[0-9]+$/",$input)){
//Input is a base-10 decimal. Multiply as necessary to remove the decimal
//point. Convert that to a gmp_resource, then decrement the exponent
//to compensate.
$pieces=explode(".", $input); //Split at the d.p.
$input="$pieces[0]$pieces[1]"; //Remove the decimal point.
$input=ltrim($input,'0');
//Remove any leading zeros, or gmp_init will parse the number as octal.
if ($input==''){ //Deal with "0.0" which would otherwise be ''.
$input=0;
}
$integer=gmp_init($input);
$ns_exponent=-strlen($pieces[1]);
//exponent = (-) the number of characters after the decimal point.
}
?>
gmp_init
(PHP 4 >= 4.0.4, PHP 5)
gmp_init — GMP 数を作成する
説明
resource gmp_init ( mixed number [, int base] )整数または文字列から GMP 数を生成します。文字列表現には、 十進数か十六進数、あるいは八進数を使用可能です。 オプションのパラメータ base は、 PHP 4.1.0 以降で使用可能です。そのデフォルト値は 0 となります。
base には 2 から 36 までの値を指定することができます。 base を 0 (デフォルト値) にすると、最初の文字に応じて実際の基数を決定します。 最初の二文字が 0x あるいは 0X の場合は十六進数、それ以外で最初の文字が "0" の場合は八進数、 それ以外の場合は十進数となります。
注意: gmp_add() のような GMP 関数において、GMP 数を 指定するところに整数または文字列を使用したい場合には、この関数を コールする必要はありません。この場合、変換が必要な場合には、 gmp_init() と同様の方法で関数の引数は自動的に GMP 数に変換されます。
gmp_init
php at richardneill dot org
20-Sep-2006 07:30
20-Sep-2006 07:30
php at richardneill dot org
20-Sep-2006 07:14
20-Sep-2006 07:14
Note: Leading zeros will make gmp_init parse this as octal.
Thus gmp_init(010) becomes 8.
$a=010; //8
$b="010" + 0; //10
$c=gmp_strval(gmp_init(010)); //8
$d=gmp_strval(gmp_init("010")); //8
This behaviour is inconsistent: either $d should equal $b, or
$b should equal $a.
thomas dot hebinck at digionline dot de
19-Aug-2005 02:23
19-Aug-2005 02:23
If you call a gmp_* function directly with an interger as parameter, this integer MUST NOT be 0:
for($i=-1;$i<=1;$i++) { echo gmp_strval(gmp_add(2,gmp_mul(1,$i))) . ' '; }
The result is 1 0 3 (wrong)
In this case you have to use gmp_init():
for($i=-1;$i<=1;$i++) { echo gmp_strval(gmp_add(2,gmp_mul(1,gmp_init($i)))) . ' '; }
The result is 1 2 3 (right)
Happy number crunching! :-)