money2

Searchβ¦

Arithmetic Operations

The Money class is immutable, so each operation returns a new Money instance.

Money uses fixed scale (no. of decimals) mathemtatics operations which can lead to some expected results.

1

import 'money2.dart';

2

/// 0 decimal place currency.

3

final Currency kr = Currency.create('KR', 0);

4

final Money amount = Money.parse(r'100', kr, 'S0');

5

final halfish = amount * 0.4;

6

print(halfish);

7

0

Copied!

`The problem with the above equation is that `amount` has a scale of 0. As we don't know the scale of the double (0.4) we use the scale of the amount. The resuls in 0.4 being rounded down to zero.`

`The correct way to handle this is to first convert the double to a Fixed instance with the desired scale.`

1

import 'money2.dart';

2

/// 0 decimal place currency.

3

final Currency kr = Currency.create('KR', 0);

4

final Money amount = Money.parse(r'100', kr, 'S0');

5

final halfish = amount * Fixed.fromNum(0.4, scale: 1);

6

print(halfish);

7

40

Copied!

`Money`

provides the following arithmetic operators:- unary
`-()`

`+(Money)`

`-(Money)`

`*(num)`

`/(num)`

`+`

`-`

`ArgumentError`

1

import 'package:money2/money2.dart';

2

final tenDollars = fiveDollars + fiveDollars;

3

final zeroDollars = fiveDollars - fiveDollars;

Copied!

Operators *schoolbook rounding* to round result up to a minorUnits of a currency.

`*`

, `/`

receive a `num`

as the second operand. Both operators use 1

import 'package:money2/money2.dart';

2

final fifteenCents = Money.fromBigInt(BigInt.from(15), code: 'USD');

3

β

4

final thirtyCents = fifteenCents * 2; // $0.30

5

final eightCents = fifteenCents * 0.5; // $0.08 (rounded from 0.075)

Copied!

Last modified 3mo ago

Copy link