Money

Working with monetary values

MaSH provides a money library which is designed to take care of all the subtle intricacies of handling money in your code. Why is this important?

A large proportion of the computers in this world manipulate money, so it’s always puzzled me that money isn’t actually a first class data type in any mainstream programming language. The lack of a type causes problems, the most obvious surrounding currencies. If all your calculations are done in a single currency, this isn’t a huge problem, but once you involve multiple currencies you want to avoid adding your dollars to your yen without taking the currency differences into account. The more subtle problem is with rounding. Monetary calculations are often rounded to the smallest currency unit. When you do this it’s easy to lose pennies (or your local equivalent) because of rounding errors.

Martin Fowler

Under the hood MaSH uses the Money for PHP package. You can read more about the package here.

Natural

# Create a 100 euro money object
set eur100 to mash.money.eur(100)

# Setup some exchange rates
set rates to {
    eur: {
        usd: 1.25
    }
}

# Create a converter using our rates
set converter to mash.money.converter(rates)

# Create a currency object
set currency to mash.money.currency('usd')

# Convert our euros to usd
set usd125 to converter.convert(eur100, currency)

printline usd125

# Share our dollars between three parties
set allocations to usd125.allocateTo(3)

printline result

Standard

# Create a 100 euro money object
eur100 = mash.money.eur(100)

# Setup some exchange rates
rates = {
    eur: {
        usd: 1.25
    }
}

# Create a converter using our rates
converter = mash.money.converter(rates)

# Create a currency object
currency = mash.money.currency('usd')

# Convert our euros to usd
usd125 = converter.convert(eur100, currency)

printline(usd125)

# Share our dollars between three parties
allocations = usd125.allocateTo(3)

printline(result)

Output

Money {
    "amount": "125",
    "currency": "USD"
}
Array [
    {
        "amount": "42",
        "currency": "USD"
    },
    {
        "amount": "42",
        "currency": "USD"
    },
    {
        "amount": "41",
        "currency": "USD"
    }
]

← All articles