package l23_5;

public class Money {
	private int dollars;
	private int cents;

	public Money() {
		this.dollars=0;
		this.cents=0;
	}

	public Money(int dollars,int cents) {
		this.dollars=dollars;
		this.cents= cents;
	}

	public Money(double dollarsAndCents) {
		dollars = (int)dollarsAndCents;
		double dCents = (dollarsAndCents-(double)dollars)*100.0;
		cents = (int) Math.round(dCents);
		double diff =  Math.abs(((double)cents)-dCents);
//System.out.println("DEBUG: cents=" + cents + " dCents=" + dCents + " difference=" +	diff);
		if (diff>0.0001 ){
			System.out.println("Fractional cents in " + dollarsAndCents + " rounded to " + this);
		}
		if (cents==100) { cents=0; dollars++; }
		if (cents==-100) { cents=0; dollars--; }
	}

	public Money(Money from) {
		this.dollars = from.dollars;
		this.cents =  from.cents;
	}

	public int getDollars() { return dollars; }

	public int getCents() { return cents; }

	public Money add(Money adder) {
		Money result = new Money();
		result.dollars = adder.dollars + this.dollars;
		result.cents = adder.cents + this.cents;
		if(result.cents>99) {
			result.cents= result.cents-100;
			result.dollars= result.dollars + 1;
		}
    	if (result.cents<0) {
			result.dollars = result.dollars - 1;
			result.cents = result.cents +100;
		}
		return result;
	}

	// A mult method to multiply the current value by a double number
	public Money mult(double multiplier) {
		double dMoney=(dollars + (cents/100.0))*multiplier;
		return new Money(dMoney);
	}

	// A compareTo method,
	//			returns int < 0 if this < that
	// 		returns 0 if this==that
	// 		returns int > 0 if this > that
	int compareTo(Money that) {
		int ddollars=this.dollars-that.dollars;
		if (ddollars != 0) return ddollars;
		return this.cents-that.cents;
	}

	public double toDouble() { return (dollars + (cents/100.0)); }

	// A toString method to represent this object as a String
	public String toString() {
		return String.format("$%d.%02d",dollars,cents);
	}

}
