Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

php-prices

> 编程语言
Open source

A simple PHP library for complex monetary prices management

171 stars0 likes0 views
WebsiteGitHub

About

A simple PHP library for complex monetary prices management

PHP Prices

Version 3.x

This new major version aims to avoid rounding errors when working with division and multiplication.

We have replaced almost all Brick\Money\Money typehints to Brick\Money\AbstractMoney in order to allow usage of Brick\Money\RationalMoney instances as the base for the price object, in order to allow rounding-free division and multiplication. See the new chapter on rounding errors in this documentation for more information.
We have also added type definitions everywhere we could. This introduces some breaking changes.

Using the underlying brick/money library, this simple Price object allows to work with complex composite monetary values which include exclusive, inclusive, VAT (and other potential taxes) and discount amounts. It makes it safer and easier to compute final displayable prices without having to worry about their construction.

Install

composer require whitecube/php-prices

Getting started

Each Price object has a base Brick\Money\Money or Brick\Money\RationalMoney instance which is considered to be the item's unchanged, per-unit & exclusive amount. All the composition operations, such as adding VAT or applying discounts, are added on top of this base value.

php
use Whitecube\Price\Price;

$steak = Price::EUR(1850)   // Steak costs €18.50/kg
    ->setUnits(1.476)       // Customer had 1.476kg, excl. total is €27.31
    ->setVat(6)             // There is 6% VAT, incl. total is €28.95
    ->addTax(50)            // There also is a €0.50/kg tax (before VAT), incl. total is €29.73
    ->addDiscount(-100);    // We granted a €1.00/kg discount (before VAT), incl. total is €28.16

It is common practice and always best to work with amounts represented in the smallest currency unit (minor values) such as "cents".

There are several convenient ways to obtain a Price instance:

Method Using major values Using minor values Defining units
Constructor new Price(AbstractMoney $base) new Price(AbstractMoney $base) new Price(AbstractMoney $base, $units)
Brick/Money API Price::of($major, $currency) Price::ofMinor($minor, $currency) -
Currency API - Price::EUR($minor) Price::USD($minor, $units)
Parsed strings Price::parse($value, $currency) - Price::parse($value, $currency, $units)

From Constructor

You can set this basic value by instantiating the Price directly with the desired Brick\Money\Money instance:

php
use Brick\Money\Money;
use Whitecube\Price\Price;

$base = new Money::ofMinor(500, 'USD');         // $5.00

$single = new Price($base);                     // 1 x $5.00
$multiple = new Price($base, 4);                // 4 x $5.00

From Brick/Money-like methods

For convenience, it is also possible to use the shorthand Money factory methods:

php
use Whitecube\Price\Price;

$major = Price::of(5, 'EUR');                   // 1 x €5.00
$minor = Price::ofMinor(500, 'USD');            // 1 x $5.00

Using these static calls, you cannot define quantities or units directly with the constructor methods.

For more information on all the available Brick/Money constructors, please take a look at their documentation.

From currency-code methods

You can also create an instance directly with the intended currency and quantities using the 3-letter currency ISO codes:

php
use Whitecube\Price\Price;

$single = Price::EUR(500);                      // 1 x €5.00
$multiple = Price::USD(500, 4);                 // 4 x $5.00

Using these static calls, all monetary values are considered minor values (e.g. cents).

For a list of all available ISO 4217 currencies, take a look at Brick/Money's iso-currencies definition.

From parsed string values

Additionnaly, prices can also be parsed from "raw currency value" strings. This method can be useful but should always be used carefully since it may produce unexpected results in some edge-case situations, especially when "guessing" the currency :

php
use Whitecube\Price\Price;

$guessCurrency = Price::parse('5,5$');          // 1 x $5.50
$betterGuess = Price::parse('JMD 5.50');        // 1 x $5.50
$forceCurrency = Price::parse('10', 'EUR');     // 1 x €10.00

$multiple = Price::parse('6.008 EUR', null, 4); // 4 x €6.01
$force = Price::parse('-5 EUR', 'USD', 4);      // 4 x $-5.00

Parsing formatted strings is a tricky subject. More information on parsing string values below.

Accessing the Money objects (getters)

Once set, the base amount can be accessed using the base() method.

Note If you give an instance of Brick\Money\Money as a parameter when instanciating the price object, you will get a Brick\Money\Money instance back. Similarly, instanciating with Brick\Money\RationalMoney will give you a RationalMoney object back.

php
$perUnit = $price->base();                      // Brick\Money\Money
$allUnits = $price->base(false);                // Brick\Money\Money

Getting the currency instance is just as easy:

php
$currency = $price->currency();                 // Brick\Money\Currency

The total exclusive amount (with all modifiers except VAT):

php
$perUnit = $price->exclusive(true);             // Brick\Money\Money
$allUnits = $price->exclusive();                // Brick\Money\Money

The total inclusive amount (with all modifiers and VAT applied):

php
$perUnit = $price->inclusive(true);             // Brick\Money\Money
$allUnits = $price->inclusive();                // Brick\Money\Money

The VAT variables:

php
$vat = $price->vat();                           // Whitecube\Price\Vat
$percentage = $price->vat()->percentage();      // float
$perUnit = $price->vat()->money(true);          // Brick\Money\Money
$allUnits = $price->vat()->money();             // Brick\Money\Money

Comparing amounts

It is possible to check whether a price object's total inclusive amount is greater, lesser or equal to another value using the compareTo method:

php
$price = Price::USD(500, 2);                    // 2 x $5.00

$price->compareTo(999);                         // 1
$price->compareTo(1000);                        // 0
$price->compareTo(1001);                        // -1

$price->compareTo(Money::of(10, 'USD'));        // 0
$price->compareTo(Price::USD(250, 4));          // 0

For convenience there also is an equals() method:

php
$price->equals(999);                            // false
$price->equals(1000);                           // true
$price->equals(Money::of(10, 'USD'));           // true
$price->equals(Price::USD(250, 4));             // true

If you don't want to compare final modified values, there is a compareBaseTo method:

php
$price = Price::USD(500, 2);                    // 2 x $5.00

$price->compareBaseTo(499);                     // 1
$price->compareBaseTo(500);                     // 0
$price->compareBaseTo(501);                     // -1

$price->compareBaseTo(Money::of(5, 'USD'));     // 0
$price->compareBaseTo(Price::USD(500, 4));      // 0

Modifying the base price

The price object will forward all the Brick\Money\Money API method calls to its base value.

Warning: In opposition to Money objects, Price objects are not immutable. Therefore, operations like plus, minus, etc. will directly modify the price's base value instead of returning a new instance.

php
use Whitecube\Price\Price;

$price = Price::ofMinor(500, 'USD')->setUnits(2);   // 2 x $5.00

$price->minus('2.00')                               // 2 x $3.00
    ->plus('1.50')                                  // 2 x $4.50
    ->dividedBy(2)                                  // 2 x $2.25
    ->multipliedBy(-3)                              // 2 x $-6.75
    ->abs();                                        // 2 x $6.75

Please refer to brick/money's documentation for the full list of available features.

Nice to know: Whenever possible, you should prefer using modifiers to alter a price since its base value is meant to be constant. For more information on modifiers, please take at the "Adding modifiers" section below.

Handling rounding properly when using division and multiplication

When creating a price object from a Brick\Money\Money instance, rounding errors can occur when doing division and multiplication.

An example of the problem: we have a base price of 1000 minor units, that we need to divide by 12 and then multiply by 11.

1000 / 12 * 11 = 916,6666666666...

Using the regular Brick\Money\Money class forces us to specify a rounding mode when doing the division, which means we have a rounded result before doing the multiplication, which introduces an error in the result:

php
use \Brick\Money\Money;
use \Whitecube\Price\Price;
use \Brick\Math\RoundingMode;

$base = Money::ofMinor(1000, 'EUR');
$price = new Price($base);

// A rounding mode is mandatory in order to do the division,
// which causes rounding errors down the line
$price->dividedBy(12, RoundingMode::HALF_UP)->multipliedBy(11);

$price->getMinorAmount(); // 913 minor units ❌

The solution is to build the Price instance with a base Brick\Money\RationalMoney instance instead, which represents the amount as a fraction and thus does not require rounding.

php
use \Brick\Money\Money;
use \Whitecube\Price\Price;
use \Brick\Math\RoundingMode;
use \Brick\Money\Context\CustomContext;

$base = Money::ofMinor(1000, 'EUR')->toRational();
$price = new Price($base);

// With RationalMoney, rounding is not necessary at this stage
$price->dividedBy(12)->multipliedBy(11);

// But rounding can occur at the very end
$price->to(new CustomContext(2), RoundingMode::HALF_UP)->getMinorAmount(); // 917 minor units ✅

For more information, see brick/money's documentation on the matter.

Setting units (quantities)

This package's default behavior is to consider its base price as the "per unit" price. When no units have been specified, it defaults to 1. Since "units" can be anything from a number of undividable products to a measurement, they are always converted to floats.

You can set the units amount (or "quantity" if you prefer) during instantiation:

php
use Whitecube\Price\Price;
use Brick\Money\Money;

$price = new Price(Money::ofMinor(500, 'EUR'), 2);      // 2 units of €5.00 each
$same = Price::EUR(500, 2);                             // same result
$again = Price::parse('5.00', 'EUR', 2);                // same result

...or modify it later using the setUnits() method:

php
$price->setUnits(1.75);                                 // 1.75 x €5.00

You can return the units count using the units() method (always float):

php
$quantity = $price->units();                            // 1.75

Setting VAT

VAT can be added by providing its relative value (eg. 21%):

php
use Whitecube\Price\Price;

$price = Price::USD(200);                   // 1 x $2.00

$price->setVat(21);                         // VA

Issues· 2 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言