PHP璇硶涓暣鍨嬩粙缁嶏紝涓涓 integer 鏄泦鍚 Z = {..., -2, -1, 0, 1, 2, ...} 涓殑涓涓暟銆
涓涓 integer 鏄泦鍚 Z = {..., -2, -1, 0, 1, 2, ...} 涓殑涓涓暟銆
鍙傝
浠绘剰闀垮害鏁存暟 / GMP
娴偣鏁
浠绘剰绮惧害鏁板搴 / BCMath
璇硶
鏁村瀷鍊煎彲浠ヤ娇鐢ㄥ崄杩涘埗锛屽崄鍏繘鍒舵垨鍏繘鍒惰〃绀猴紝鍓嶉潰鍙互鍔犱笂鍙夌殑绗﹀彿锛- 鎴栬 +锛夈
鍏繘鍒惰〃绀烘暟瀛楀墠蹇呴』鍔犱笂 0锛堥浂锛夛紝鍗佸叚杩涘埗琛ㄧず鏁板瓧鍓嶅繀椤诲姞涓 0x銆
Example #1 鏁存暟鏂囧瓧琛ㄨ揪
<?php
$a = 1234; // 鍗佽繘鍒舵暟
$a = -123; // 璐熸暟
$a = 0123; // 鍏繘鍒舵暟 (绛変簬鍗佽繘鍒 83)
$a = 0x1A; // 鍗佸叚杩涘埗鏁 (绛変簬鍗佽繘鍒 26)
?>
鏁村瀷(integer)鐨勫舰寮忔弿杩帮細
decimal : [1-9][0-9]*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
鏁村瀷鏁扮殑瀛楅暱鍜屽钩鍙版湁鍏筹紝灏界閫氬父鏈澶у兼槸澶х害浜屽崄浜匡紙32 浣嶆湁绗﹀彿锛夈侾HP 涓嶆敮鎸佹棤绗﹀彿鏁存暟銆侷nteger鍊肩殑瀛楅暱鍙互鐢ㄥ父閲廝HP_INT_SIZE鏉ヨ〃绀猴紝鑷 PHP 4.4.0 鍜 PHP 5.0.5鍚庯紝鏈澶у煎彲浠ョ敤甯搁噺PHP_INT_MAX鏉ヨ〃绀恒
Warning
濡傛灉鍚戝叓杩涘埗鏁颁紶閫掍簡涓涓潪娉曟暟瀛楋紙鍗 8 鎴 9锛夛紝鍒欏悗闈㈠叾浣欐暟瀛椾細琚拷鐣ャ
Example #2 鍏繘鍒舵暟鐨勬簨
<?php
var_dump(01090); // 鍏繘鍒 010 = 鍗佽繘鍒 8
?>
鏁存暟婧㈠嚭
濡傛灉缁欏畾鐨勪竴涓暟瓒呭嚭浜 integer 鐨勮寖鍥达紝灏嗕細琚В閲婁负 float銆傚悓鏍峰鏋滄墽琛岀殑杩愮畻缁撴灉瓒呭嚭浜 integer 鑼冨洿锛屼篃浼氳繑鍥 float銆
<?php
$large_number = 2147483647;
var_dump($large_number);
// 杈撳嚭涓猴細int(2147483647)
$large_number = 2147483648;
var_dump($large_number);
// 杈撳嚭涓猴細float(2147483648)
// 鍚屾牱涔熼傜敤浜庡崄鍏繘鍒惰〃绀虹殑鏁存暟锛 浠 2^31 鍒 2^32-1:
var_dump( 0xffffffff );
// 杈撳嚭: float(4294967295)
// 涓嶉傜敤浜庡ぇ浜 2^32-1 鐨勫崄鍏繘鍒惰〃绀虹殑鏁:
var_dump( 0x100000000 );
// 杈撳嚭: int(2147483647)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number);
// 杈撳嚭: float(50000000000)
?> Warning
涓嶅垢鐨勬槸 PHP 涓湁涓 bug锛屽洜姝ゅ綋鏈夎礋鏁板弬涓庢椂缁撴灉骞朵笉鎬绘槸姝g‘銆備緥濡傚綋杩愮畻 -50000 * $million 鏃剁粨鏋滄槸 -429496728銆備笉杩囧綋涓や釜杩愮畻鏁伴兘鏄鏁版椂灏辨病闂銆
杩欎釜闂宸茬粡鍦 PHP 4.1.0 涓В鍐充簡銆
PHP 涓病鏈夋暣闄ょ殑杩愮畻绗︺1/2 浜х敓鍑 float 0.5銆傚彲浠ユ绘槸鑸嶅純灏忔暟閮ㄥ垎锛屾垨鑰呬娇鐢 round() 鍑芥暟銆 There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
杞崲涓烘暣鍨
瑕佹槑纭湴灏嗕竴涓艰浆鎹负 integer锛岀敤 (int) 鎴 (integer) 寮哄埗杞崲銆備笉杩囧ぇ澶氭暟鎯呭喌涓嬮兘涓嶉渶瑕佸己鍒惰浆鎹紝鍥犱负褰撹繍绠楃锛屽嚱鏁版垨娴佺▼鎺у埗闇瑕佷竴涓 integer 鍙傛暟鏃讹紝鍊间細鑷姩杞崲銆傝繕鍙互閫氳繃鍑芥暟 intval() 鏉ュ皢涓涓艰浆鎹㈡垚鏁村瀷銆
鍙傝: 绫诲瀷杞崲鐨勫垽鍒.
浠庡竷灏斿艰浆鎹
FALSE 灏嗕骇鐢熷嚭 0锛堥浂锛夛紝TRUE 灏嗕骇鐢熷嚭 1锛堝9锛夈
浠庢诞鐐规暟杞崲
褰撲粠娴偣鏁拌浆鎹㈡垚鏁存暟鏃讹紝灏嗗悜闆跺彇鏁淬
濡傛灉娴偣鏁拌秴鍑轰簡鏁存暟鑼冨洿锛堥氬父涓 +/- 2.15e+9 = 2^31锛夛紝鍒欑粨鏋滀笉纭畾锛屽洜涓烘病鏈夎冻澶熺殑绮惧害浣挎诞鐐规暟缁欏嚭涓涓‘鍒囩殑鏁存暟缁撴灉銆傚湪姝ゆ儏鍐典笅娌℃湁璀﹀憡锛岀敋鑷虫病鏈変换浣曢氱煡锛
Warning
鍐充笉瑕佸皢鏈煡鐨勫垎鏁板己鍒惰浆鎹负 integer锛岃繖鏍锋湁鏃朵細瀵艰嚧涓嶅彲棰勬枡鐨勭粨鏋溿
<?php
echo (int) ( (0.1+0.7) * 10 ); // 鏄剧ず 7!
?>
鍙傝 鍏充簬娴偣鏁扮簿搴︾殑璀﹀憡銆
浠庡瓧绗︿覆杞崲
鍙傝 瀛楃涓茶浆鎹负鏁板瓧
浠庡叾瀹冪被鍨嬭浆鎹
Caution
娌℃湁瀹氫箟浠庡叾瀹冪被鍨嬭浆鎹负鏁村瀷鐨勮涓恒備笉瑕佷緷璧栦换浣曞彲瑙佺殑琛屼负锛屽洜涓哄畠浼氭湭鍔犻氱煡鍦版敼鍙樸 The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.
浠ヤ笂灏辨槸PHP绫诲瀷涔嬫暣鍨嬩粙缁嶇殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒