money

Holds an amount of money *

Constructors

this
this(double x)

Usual contructor. Uses rmode on x.

Members

Aliases

T
alias T = typeof(this)
Undocumented in source.

Functions

opBinary
T opBinary(T rhs)

Can add and subtract money amounts of the same type.

opBinary
T opBinary(long rhs)

Can multiply, divide, and modulo with integer values.

opBinary
T opBinary(real rhs)

Can multiply, divide, and modulo floating point numbers.

opCmp
int opCmp(OT other)

Can compare with money amounts of the same concurrency.

opEquals
bool opEquals(OT other)

Can check equality with money amounts of the same concurrency and decimal places.

toString
void toString(void delegate(const(char)[]) sink, FormatSpec!char fmt)

Can convert to string.

Manifest constants

__currency
enum __currency;
Undocumented in source.
__dec_places
enum __dec_places;
Undocumented in source.
__rmode
enum __rmode;
Undocumented in source.

Static variables

init
auto init;

default initialisation value is zero

max
auto max;

maximum amount depends on dec_places

min
auto min;

minimum amount depends on dec_places

Variables

amount
long amount;
Undocumented in source.

Examples

Basic usage

alias EUR = money!("EUR");
assert(EUR(100.0001) == EUR(100.00009));
assert(EUR(3.10) + EUR(1.40) == EUR(4.50));
assert(EUR(3.10) - EUR(1.40) == EUR(1.70));
assert(EUR(10.01) * 1.1 == EUR(11.011));

import std.format : format;

// for writefln("%d", EUR(3.6));
assert(format("%d", EUR(3.6)) == "4EUR");
assert(format("%d", EUR(3.1)) == "3EUR");
// for writefln("%f", EUR(3.141592));
assert(format("%f", EUR(3.141592)) == "3.1416EUR");
assert(format("%.2f", EUR(3.145)) == "3.15EUR");

Overflow is an error, since silent corruption is worse

import std.exception : assertThrown;

alias EUR = money!("EUR");
auto one = EUR(1);
assertThrown!OverflowException(EUR.max + one);
assertThrown!OverflowException(EUR.min - one);

Arithmetic ignores rounding mode

alias EUR = money!("EUR", 2, roundingMode.UP);
auto one = EUR(1);
assert(one != one / 3);

Generic equality and order

alias USD = money!("USD", 2);
alias EURa = money!("EUR", 2);
alias EURb = money!("EUR", 4);
alias EURc = money!("EUR", 4, roundingMode.DOWN);
// cannot compile with different currencies
static assert(!__traits(compiles, EURa(1) == USD(1)));
// cannot compile with different dec_places
static assert(!__traits(compiles, EURa(1) == EURb(1)));
// can check equality if only rounding mode differs
assert(EURb(1.01) == EURc(1.01));
// cannot compare with different currencies
static assert(!__traits(compiles, EURa(1) < USD(1)));

Meta