> 백엔드 개발 > PHP 튜토리얼 > 새로운 BCMath 개체 API를 사용하여 PHP에서 소수 계산 처리

새로운 BCMath 개체 API를 사용하여 PHP에서 소수 계산 처리

Patricia Arquette
풀어 주다: 2025-01-23 12:04:11
원래의
919명이 탐색했습니다.

Handling Decimal Calculations in PHP  with the New BCMath Object API

원본은 유 타케시 블로그에 게재되었습니다.


정확한 수치 계산은 기업 애플리케이션, 특히 재무, 회계 또는 재고를 다루는 애플리케이션에서 가장 중요합니다. 사소한 반올림 오류라도 심각한 문제를 일으킬 수 있습니다. PHP 8.4의 향상된 BCMath 개체 API는 정확하고 효율적인 십진수 계산을 위한 개선된 솔루션을 제공합니다.


숙련된 PHP 개발자는 부동 소수점 부정확성에 익숙합니다.

<code class="language-php">$a = 0.1;
$b = 0.2;
var_dump($a + $b);  // Outputs: 0.30000000000000004</code>
로그인 후 복사

이러한 부정확성은 재정적 측면에서 용납될 수 없습니다. 이러한 작은 오류가 누적되어 실제 불일치로 이어집니다.

정밀성을 위한 데이터베이스 설계

정확한 소수 계산은 데이터베이스에서 시작됩니다. DECIMAL 유형은 필수입니다.

<code class="language-php">// In Laravel Migration
Schema::create('items', function (Blueprint $table) {
    $table->id();
    $table->decimal('quantity', 10, 3);  // Precision: 10 digits, 3 decimal places
    $table->decimal('price', 10, 3);     // Precision: 10 digits, 3 decimal places
    $table->decimal('discount', 10, 3);  // Precision: 10 digits, 3 decimal places
    $table->decimal('tax', 10, 3);       // Precision: 10 digits, 3 decimal places
    // ... other columns
});</code>
로그인 후 복사

DECIMAL 보장:

  • 정확한 소수점 이하 자릿수.
  • 맞춤형 규모와 정밀도.
  • 금융 애플리케이션에 적합합니다.

FLOAT보다 약간 느릴 수 있지만 미션 크리티컬 시스템의 성능 차이보다 정밀성 이점이 더 큽니다.

Laravel의 캐스팅 활용

Laravel은 캐스팅 시스템을 통해 소수점 처리를 단순화합니다.

<code class="language-php">class Item extends Model
{
    protected $casts = [
        'quantity' => 'decimal:3',
        'price' => 'decimal:3',
        'discount' => 'decimal:3',
        'tax' => 'decimal:3',
    ];
}</code>
로그인 후 복사

그러나 Laravel 캐스팅은 주로 다음을 관리한다는 점을 기억하세요.

  • 데이터 형식화.
  • 일관적인 가치 표현.

유형 변환 함정 방지

올바른 데이터베이스 유형과 Laravel 캐스팅이 있어도 계산 오류가 발생할 수 있습니다.

<code class="language-php">// Database values
$item1 = Item::find(1);  // price: "99.99"
$item2 = Item::find(2);  // price: "149.99"

// Calculation without BCMath
$subtotal = $item1->price + $item2->price;
$tax = $subtotal * 0.05;  // 5% tax

var_dump($tax);  // Outputs: float(12.499000000000002) instead of 12.499</code>
로그인 후 복사

이 문제는 PHP가 연산 중에 암시적으로 문자열을 숫자로 변환하기 때문에 발생합니다.

<code class="language-php">// String values from database
$price1 = "99.99";
$price2 = "149.99";
echo gettype($price1);  // string

// Implicit conversion to float
$total = $price1 + $price2;
echo gettype($total);   // double (float)</code>
로그인 후 복사

PHP 8.4 이전의 BCMath: 정확하지만 지루함

기존 BCMath 확장은 정밀도를 제공합니다.

<code class="language-php">// Database values
$item1 = Item::find(1);  // price: "99.99"
$item2 = Item::find(2);  // price: "149.99"

// Using BCMath functions
$subtotal = bcadd($item1->price, $item2->price, 3);
$tax = bcmul($subtotal, $item2->tax, 3);

var_dump($tax);  // Precisely outputs: string(5) "12.499"</code>
로그인 후 복사

그러나 복잡한 계산은 장황해지고 유지 관리가 어려워집니다.

<code class="language-php">// Complex order calculation (using BCMath functions)
// ... (code omitted for brevity)</code>
로그인 후 복사

PHP 8.4의 BCMath 객체 API: 우아함과 정확성

PHP 8.4의 객체 지향 BCMath API는 정확한 계산을 단순화합니다.

<code class="language-php">use BCMath\Number;

$item1 = Item::find(1);
$price = new Number($item1->price);
$quantity = new Number($item1->quantity);
$discountRate = new Number($item1->discount);
$taxRate = new Number($item1->tax);

// Natural and readable calculations
$subtotal = $price * $quantity;
$discount = $subtotal * $discountRate;
$afterDiscount = $subtotal - $discount;
$tax = $afterDiscount * $taxRate;
$total = $afterDiscount + $tax;

var_dump($total);  // Automatically converts to string</code>
로그인 후 복사

새 API의 장점:

  • 직관적인 객체지향 디자인.
  • 표준 수학 연산자를 지원합니다.
  • 데이터 무결성을 위한 불변 객체.
  • Stringable 인터페이스 구현

원활한 라라벨 통합

Laravel의 접근자를 사용하면 더욱 우아함을 얻을 수 있습니다.

<code class="language-php">use BCMath\Number;

class Item extends Model
{
    // ... (accessor methods for quantity, price, discount, tax using Number) ...
}</code>
로그인 후 복사

또는 맞춤형 캐스트를 사용하는 경우:

<code class="language-php">// ... (DecimalCast class implementation) ...</code>
로그인 후 복사

그런 다음:

<code class="language-php">$item1 = Item::find(1);

$subtotal = $item1->price * $item1->quantity;
// ... (rest of the calculation) ...</code>
로그인 후 복사

결론

헬스케어 재고관리에서는 정확한 소수점 계산이 중요합니다. Laravel과 통합된 PHP 8.4의 BCMath 개체 API는 이러한 계산 처리를 크게 향상시켜 정밀도, 가독성, 유지 관리 가능성 및 유형 안전성을 제공합니다. 이전 BCMath 기능은 목적을 달성했지만 이 새로운 접근 방식은 개발을 상당히 간소화합니다.

위 내용은 새로운 BCMath 개체 API를 사용하여 PHP에서 소수 계산 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿