찾다
백엔드 개발PHP 튜토리얼Integers and Floating point numbers in PHP

原文:http://www.ebrueggeman.com/blog/integers-and-floating-numbers/ Background

PHP is not a strictly typed language, and many programmers often overlook problems that can be caused with not paying attention to numeric types. The problem is that PHP does not alert you when you have gone outside of the bounds of what an integer can hold. Instead, it silently converts your value to a float (floating point number.)

Why should you care? Mathematic expressions with floats are not always exact ? sometimes they can be way off. PHP, like most programming languages, uses shortcuts to estimate the result of floating point mathematic expressions. The rule of thumb is that the larger the numbers you are working with, the greater amount of estimations involved in finding a result. If you were programming a PHP-based financial application, this could be a huge liability.

The best way to handle large numbers in PHP is to be aware of exactly what type of number you are dealing by knowing the PHP bounds of integers. PHP supplies a constant PHP_INT_MAX which will tell you what the maximum integer is for your instance of PHP. Not all computers/operating systems/versions of PHP are the same, so it is good to find the PHP_INT_MAX for each setup. Note that the PHP_INT_MAX also determines the smallest negative number ? just multiply it by -1 to get the PHP integer minimum.

PHP Integer Testing Script

Below is a testing script to help you determine the PHP_INT_MAX:

<?php$intMax = PHP_INT_MAX;   echo "$intMax<br />";   if (is_int($intMax)) {	echo "$intMax is an Int<br />";}else {	echo "$intMax is NOT an Int<br />";}   if (is_int($intMax + 1)) {	echo "$intMax+1 is an Int<br />";}else {	echo "$intMax+1 is NOT an Int<br />";}   if (is_int($intMax * (-1))) {	echo "$intMax*(-1) is an Int<br />";}else {	echo "$intMax*(-1) is NOT an Int<br />";}?>

The result of this script:

21474836472147483647 is an Int2147483647+1 is NOT an Int2147483647*(-1) is an Int
PHP Float Testing Script

Now that you know the bounds of integers, what do you do? Truth be told, there is not a whole lot you can do to guarantee the integrity of your floating point numbers. It may be more important to know which figures are the result of math involving floating point numbers, so you can disclose this to your audience, and act accordingly. See the simple example below that shows how poorly PHP can do math involving floating point numbers:

<?php//TEST 1$number = 216897510871;$original_number = $number;   $number *= 11123.74;$number /= 11123.74;   if ($original_number == $number) {	echo "Test 1: Are Equal<br />";}else {	echo "Test 1: Are NOT Equal<br />";}   //TEST 2$number = 216897510871;$original_number = $number;   $number *= 11123.75;$number /= 11123.75;   if ($original_number == $number) {	echo "Test 2: Are Equal<br />";}else {	echo "Test 2: Are NOT Equal<br />";}?>

The result of this script:

Test 1: Are EqualTest 2: Are NOT Equal
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP의 종속성 주입이란 무엇입니까?PHP의 종속성 주입이란 무엇입니까?May 07, 2025 pm 03:09 PM

expendencyInphpisaDesignpatternpattern thatenhances-flexibility, testability 및 maintainabilitable externaldenciestoclasses.itallowsforloosecoupling, easiertesting throughmocking 및 modulardesign, berrequirecarefultructuringtoavoid-inje

최고의 PHP 성능 최적화 기술최고의 PHP 성능 최적화 기술May 07, 2025 pm 03:05 PM

PHP 성능 최적화는 다음 단계를 통해 달성 할 수 있습니다. 1) 스크립트 상단에 require_once 또는 include_once를 사용하여 파일로드 수를 줄입니다. 2) 데이터베이스 쿼리 수를 줄이기 위해 전처리 문 및 배치 처리를 사용하십시오. 3) Opcode 캐시에 대한 Opcache 구성; 4) PHP-FPM 최적화 프로세스 관리를 활성화하고 구성합니다. 5) CDN을 사용하여 정적 자원을 배포합니다. 6) 코드 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하십시오. 7) 배열과 같은 효율적인 데이터 구조를 선택하십시오. 8) 최적화 실행을위한 모듈 식 코드를 작성하십시오.

PHP 성능 최적화 : Opcode 캐싱 사용PHP 성능 최적화 : Opcode 캐싱 사용May 07, 2025 pm 02:49 PM

opCodeCachingsIntIficInlyIntImeRimproveSphpperformanceCachingCompileDCode, retingServerLoadandResponsEtimes.1) itStoresCompyledPhpCodeInMemory, BYPASSINGPARSINGCOMPILING.2) UseOpCacheSettingParametersInphP.Ini, likeMoryConsAncme AD

PHP 의존성 주입 : 코드 유지 관리를 향상시킵니다PHP 의존성 주입 : 코드 유지 관리를 향상시킵니다May 07, 2025 pm 02:37 PM

종속성 주입은 PHP의 외부 주입을 통해 객체 종속성을 제공하여 코드의 유지 관리 및 유연성을 향상시킵니다. 구현 방법에는 다음이 포함됩니다. 1. 생성자 주입, 2. 값 주입 세트, 3. 인터페이스 주입. 종속성 주입을 사용하면 분리되어 테스트 성과 유연성을 향상시킬 수 있지만 복잡성과 성능 오버 헤드가 증가 할 가능성에주의를 기울여야합니다.

PHP에서 의존성 주입을 구현하는 방법PHP에서 의존성 주입을 구현하는 방법May 07, 2025 pm 02:33 PM

PHP에서 의존성 주입 (DI) 구현은 수동 주입 또는 DI 컨테이너를 사용하여 수행 할 수 있습니다. 1) 수동 주입은 Userservice 클래스 주입 로거와 같은 생성자를 통해 종속성을 통과합니다. 2) DI 컨테이너를 사용하여 컨테이너 클래스와 같은 종속성을 자동으로 관리하여 로거 및 사용자 서비스를 관리합니다. DI를 구현하면 코드 유연성 및 테스트 가능성을 향상시킬 수 있지만 오버 삽입 및 서비스 로케이터 안티 모드와 같은 트랩에주의를 기울여야합니다.

unset ()와 session_destroy ()의 차이점은 무엇입니까?unset ()와 session_destroy ()의 차이점은 무엇입니까?May 04, 2025 am 12:19 AM

thedifferencebetweenUnset () andsession_destroy () istssection_destroy () thinatesTheentiresession.1) TEREMOVECIFICESSESSION 'STERSESSIVEBLESSESSIVESTIETSTESTERSALLS'SSOVERSOLLS '를 사용하는 것들

로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?May 04, 2025 am 12:16 AM

stickysessionsureSureSureRequestSaroutEdToTheSERSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESINCENSENCY

PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?May 04, 2025 am 12:14 AM

phpoffersvarioussessionsaveAndlers : 1) 파일 : 기본, 단순, 단순한 BUTMAYBOTTLENECKONHIGH-TRAFFICSITES.2) MEMCACHED : 고성능, IdealForspeed-CriticalApplications.3) Redis : SimilartomemCached, WithaddedPersistence.4) 데이터베일 : OffforIntegrati

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기