원본은 유 타케시 블로그에 게재되었습니다.
정확한 수치 계산은 기업 애플리케이션, 특히 재무, 회계 또는 재고를 다루는 애플리케이션에서 가장 중요합니다. 사소한 반올림 오류라도 심각한 문제를 일으킬 수 있습니다. 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은 캐스팅 시스템을 통해 소수점 처리를 단순화합니다.
<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>
기존 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는 정확한 계산을 단순화합니다.
<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 중국어 웹사이트의 기타 관련 기사를 참조하세요!