main
 1using System;
 2using gorilla.commons.utility;
 3
 4namespace MoMoney.Domain.Core
 5{
 6    [Serializable]
 7    public class Money : IEquatable<Money>
 8    {
 9        readonly long dollars;
10        readonly int cents;
11
12        public Money(long dollars) : this(dollars, 0) {}
13
14        public Money(long dollars, int cents)
15        {
16            this.dollars = dollars;
17            this.cents = cents;
18            if (this.cents >= 100)
19            {
20                this.dollars += (this.cents/100).to_long();
21                this.cents = this.cents%100;
22            }
23        }
24
25        public Money add(Money other)
26        {
27            var new_dollars = dollars + other.dollars;
28            if (other.cents + cents > 100)
29            {
30                ++new_dollars;
31                var pennies = cents + other.cents - 100;
32                return new Money(new_dollars, pennies);
33            }
34            return new Money(new_dollars, cents + other.cents);
35        }
36
37        public bool Equals(Money other)
38        {
39            if (ReferenceEquals(null, other)) return false;
40            if (ReferenceEquals(this, other)) return true;
41            return other.dollars == dollars && other.cents == cents;
42        }
43
44        public override bool Equals(object obj)
45        {
46            if (ReferenceEquals(null, obj)) return false;
47            if (ReferenceEquals(this, obj)) return true;
48            if (obj.GetType() != typeof (Money)) return false;
49            return Equals((Money) obj);
50        }
51
52        public override int GetHashCode()
53        {
54            unchecked
55            {
56                return (dollars.GetHashCode()*397) ^ cents;
57            }
58        }
59
60        static public bool operator ==(Money left, Money right)
61        {
62            return Equals(left, right);
63        }
64
65        static public bool operator !=(Money left, Money right)
66        {
67            return !Equals(left, right);
68        }
69
70        public override string ToString()
71        {
72            return "{0}.{1:d2}".formatted_using(dollars, cents);
73        }
74    }
75}