Create a Money class in C# that has as data members dollars and cents. Include I
ID: 3676143 • Letter: C
Question
Create a Money class in C# that has as data members dollars and cents. Include IncrementMoney and DecrementMoney instance methods. Include constructors that enable the Money class to be instantiated with a single value representing the full dollar/cent amount as well as a constructor that enables you to create an instance of the class by sending two separate integer values representing the dollar and cent amounts. Include an instance method that returns as a string the number of dollars, quarters, nickels, dimes, and pennies represented by the object’s value. Override the ToString( ) method to return the monetary amount formatted with currency symbols. Create a second class to test your Money class.
Explanation / Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Business_Layer
{
class Money
{
//declare class wide private vars
private decimal dollars = 0.0m;
private decimal cents = 0.0m;
private decimal totalAmount = 0.0m;
private decimal qtrs;
private decimal dimes;
private decimal nickels;
private decimal pennies;
//default const
public Money()
{
}
//const that allows total
public Money(decimal totalAmount)
{
this.totalAmount = totalAmount;
//convert to dollars and cents
dollars = Math.Floor(totalAmount);
cents = (totalAmount%1);
BreakDown();
}
//const that takes dollars and cents
public Money(decimal dollars, decimal cents)
{
this.dollars = dollars;
this.cents = cents;
this.totalAmount = dollars + cents;
}
//money incrementor
public void IncrementMoney(decimal amount)
{
//new amount is added, dollars/cents recalculated
this.totalAmount += amount;
dollars = Math.Floor(totalAmount);
cents = (totalAmount % 1);
}
//money decrementor
public void DecrementMoney(decimal amount)
{
//new amount is subtracted, dollars/cents recalculated
this.totalAmount -= amount;
dollars = Math.Floor(totalAmount);
cents = (totalAmount % 1);
}
//break down the amounts
public void BreakDown()
{
//the remainder in this case, is what we derive change from
decimal remainder = cents;
//get the quarters, store the remainder
//get the dimes, store the remainder
//rinse, repeat
qtrs = Math.Floor(remainder / .25m);
remainder = remainder % .25m;
dimes = Math.Floor(remainder / .10m);
remainder = remainder % .10m;
nickels = Math.Floor(remainder / .5m);
remainder = remainder % .5m;
//the remainder has to be pennies.
pennies = remainder;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if(dollars>0){sb.AppendLine("Dollars: " + dollars);}
if(qtrs > 0){sb.AppendLine("Quarters: " + qtrs);}
if(dimes > 0){sb.AppendLine("Dimes: " + dimes);}
if(nickels > 0){sb.AppendLine("Nickles: " + nickels);}
if(Math.Round(pennies*100)>0){sb.AppendLine("Pennies: " + Math.Round(pennies*100));}
return sb.ToString();
}
}
}