Money

Money class for your applications

Handling Money with PHP is not so fun and game, is it?

To build a great app, you have to have a great abstraction ahead for the Money type, especially if your apps are going to work closely with the money, eg:

  • Finance

  • E-commerce

  • Logistic

  • ...

Worry not, ShipSaaS got your back with the Moneyclass, features:

  • Immutable by default, money is pretty important, ya know.

  • Super lightweight yet strong helper

Glossary

Money class use int and stores your money as cents. So:

  • $6 => 600

  • $5.99 => 599

  • ...

In this way, we will never get the "floating-point" issues (for all langs & DB engines)

Never use float for Money (for all langs). Learn more at: https://sethphat.dev/type-for-money

Usage

Create a new Money instance

use SaasReady\Helpers\Money;

$money = new Money(10_00, CurrencyCode::UNITED_STATES_DOLLAR); // $10.00
$money2 = Money::make(15_99, CurrencyCode::SINGAPORE_DOLLAR); // S$15.99
$money3 = Money::makeFromRealAmount(10.99, CurrencyCode::UNITED_STATE_DOLLAR); // $10.99

Clone

$money = new Money(10_00, CurrencyCode::UNITED_STATES_DOLLAR); // $10.00
$otherMoney = $money->clone(); // $10.00

$otherMoneyButSameCurrency = $money->clone(1500_00); // $1500.00

Aggregators

There are some built-in methods that would help you to do the math:

$money->add($otherMoney);
$money->subtract($otherMoney);
$money->multiply(2);
$money->divide(5);

Present

You also can get the human-readable text to show up to your users.

It will generate the text based on the currencies configuration.

$money = new Money(10_00, CurrencyCode::UNITED_STATES_DOLLAR);

$money->present(); // $10.00 (uses symbol and decimals)
$money->present(false); // USD 10.00 (uses currency code and decimals)
$money->present(true, false); // $10 (uses symbol)
$money->present(false, false); // USD 10 (uses currency code)

Last updated