In this chapter, you will learn how to count money. It’s pretty simple, but you need to use some common sense.
Currency Conversion
Performing simple economic calculations usually means doing currency conversions , which you will try in this section.
Task
After accepting an amount in euros and the euro exchange rate, you will convert the amount to dollars (see Figure 10-1).
Figure 10-1 Converting to dollars
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter amount in euros: ");
string inputEuros = Console.ReadLine();
double amountEuros = Convert.ToDouble(inputEuros);
Console.Write("Enter euro exchange rate (how many dollars per 1 euro): ");
string inputExchangeRate = Console.ReadLine();
double euroEchangeRate = Convert.ToDouble(inputExchangeRate);
// Calculation
double amountDollars = amountEuros * euroEchangeRate;
// Output
Console.WriteLine();
Console.WriteLine("Amount in dollars: " + amountDollars);
// Waiting for Enter
Console.ReadLine();
}
Total Price
In this exercise, you will calculate the total price of an order.
Task
Say one of your customers buys several items, some of them possibly multiple times. You need to calculate the total price including the shipping cost. In this program, the prices and amounts of two products, as well as the shipping price, will be fixed directly in the source code for simplicity (see Figure 10-2).
Figure 10-2 Calculating total costs
Solution
Here is the code:
static void Main(string[] args)
{
// Fixed values
const double bookPrice = 29.8;
const double dvdPrice = 9.9;
const double shipmentPrice = 25;
// Inputs
Console.WriteLine("Order");
Console.WriteLine("-----");
Console.Write("Product "C# Programming for Absolute Beginners (book)" - enter number of pieces: ");
string inputBookPieces = Console.ReadLine();
int bookPieces = Convert.ToInt32(inputBookPieces);
Console.Write("Product "All Quiet on Western Front (DVD)" - enter number of pieces: ");
string inputDvdPieces = Console.ReadLine();
int dvdPieces = Convert.ToInt32(inputDvdPieces);
// Calculations
double totalForBook = bookPrice * bookPieces;
double totalForDvd = dvdPrice * dvdPieces;
double totalForOrder = totalForBook + totalForDvd + shipmentPrice;
// Outputs
Console.WriteLine();
Console.WriteLine("Order calculation");
Console.WriteLine("-----------------");
Console.WriteLine("Book: " + totalForBook);
Console.WriteLine("Dvd: " + totalForDvd);
Console.WriteLine("Shipment: " + shipmentPrice);
Console.WriteLine("TOTAL: " + totalForOrder);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Prepending fixed “variables” with const says they are constants, which are values that are not going to change in the course of the program run. Visual Studio does not allow you to assign new values to these “variables.”
Personally, I do not use const often. I just wanted to show it to you in case you see it during the course of your work.
Commissions
In capitalism, what matters most is not to create, produce, or plant something. The most important thing is to sell! And the person selling usually gets a commission, so you must learn how to calculate that.
Task
You will write a program that accepts the price of a product and then calculates the percentage of commission for the merchant, distributor, and producer. From the data, it also calculates the income division among the three parties (see Figure 10-3).
Figure 10-3 Calculating commissions
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter customer price of product: ");
string inputPrice = Console.ReadLine();
double customerPrice = Convert.ToDouble(inputPrice);
Console.Write("Enter merchant commission (percents): ");
string inputMerchantPercents = Console.ReadLine();
int merchantPercents = Convert.ToInt32(inputMerchantPercents);
Console.Write("Enter distributor commission (percents): ");
string inputDistributorPercents = Console.ReadLine();
int distributorPercents = Convert.ToInt32(inputDistributorPercents);
// Calculations
double coeficient1 = 1 - merchantPercents / 100.0;
double coeficient2 = 1 - distributorPercents / 100.0;
double wholesalePrice = customerPrice * coeficient1;
double priceAfterCommissionSubtraction = wholesalePrice * coeficient2;
double merchantIncome = customerPrice - wholesalePrice;
double distributorIncome = wholesalePrice - priceAfterCommissionSubtraction;
double producerIncome = priceAfterCommissionSubtraction;
// Outputs
Console.WriteLine();
Console.WriteLine("Income division");
Console.WriteLine("----------------");
Console.WriteLine("Merchant: " + merchantIncome);
Console.WriteLine("Distributor: " + distributorIncome);
Console.WriteLine("Producer: " + producerIncome);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Sometimes commission percentages might be decimal numbers . I have chosen integers in this example because I wanted to show you how to correctly divide integers with a practical example. As you know, to perform “normal” division, you need at least one number—either in front of or after a slash—to be a double. That is why you use 100.0.
If you used 100 instead, the result would be surprising (see Figure 10-4).
Figure 10-4 Commission percents, incorrect
Do you know why this happens? It’s all because of rounding.
Rounding
Money amounts are usually being rounded to cents. I will show you how to do this and what the difference is between rounding just for output and rounding for further calculations. The difference is small but sometimes significant. You might miss a cent and cause a problem for someone.
Task
After the user enters two monetary amounts (possibly somehow calculated with more than two decimal places), the program will display them with percent precision, round them to cents, and finally compare the calculation with the original values to the one with rounded values (Figure 10-5).
Figure 10-5 Rounding program
Solution
Here is the code:
static void Main(string[] args)
{
// For simplicity, inputs are fixed in program
// Some amounts, e.g. after commission calculations, cent fractions are possible
double amount1 = 1234.567;
double amount2 = 9.876;
// Displaying inputs (original values)
Console.WriteLine("First amount (original value): " + amount1);
Console.WriteLine("Second amount (original value): " + amount2);
Console.WriteLine();
// Rounding just for output
Console.WriteLine("First amount displayed with cent precision: " + amount1.ToString("N2"));
Console.WriteLine("Second amount displayed with cent precision: " + amount2.ToString("N2"));
Console.WriteLine();
// Rounding for further calculations + informative output
double roundedAmount1 = Math.Round(amount1, 2); // 2 = two decimal places
double roundedAmount2 = Math.Round(amount2, 2);
Console.WriteLine("First amount rounded to cents: " + roundedAmount1);
Console.WriteLine("Second amount rounded to cents: " + roundedAmount2);
Console.WriteLine();
// Calculations
double sumOfOriginalAmounts = amount1 + amount2;
double sumOfRoundedAmounts = roundedAmount1 + roundedAmount2;
// Calculation outputs
Console.WriteLine("Sum of original amounts: " + sumOfOriginalAmounts.ToString("N2"));
Console.WriteLine("Sum of rounded amounts: " + sumOfRoundedAmounts.ToString("N2"));
Console.WriteLine("On invoice, we need sum of rounded amounts");
// Waiting for Enter
Console.ReadLine();
}
Further Rounding
Sometimes rounding can be more complicated .
Task
In this task, I will show you how to round to dollars, round to hundreds of dollars, always round down, and always round up (see Figure 10-6 and Figure 10-7).
Figure 10-6 More complicated rounding
Figure 10-7 Another number to round to dollars, cents, and hundreds of dollars
Solution
Here is the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter (decimal) amount in dollars: ");
string input = Console.ReadLine();
double amount = Convert.ToDouble(input);
// To dollars
double nearest = Math.Round(amount);
double alwaysDown = Math.Floor(amount);
double alwaysUp = Math.Ceiling(amount);
Console.WriteLine();
Console.WriteLine("To dollars");
Console.WriteLine("----------");
Console.WriteLine("Nearest : " + nearest);
Console.WriteLine("Always down: " + alwaysDown);
Console.WriteLine("Always up : " + alwaysUp);
// To cents
nearest = Math.Round(amount, 2);
alwaysDown = Math.Floor(100 * amount) / 100;
alwaysUp = Math.Ceiling(100 * amount) / 100;
Console.WriteLine();
Console.WriteLine("To cents");
Console.WriteLine("--------");
Console.WriteLine("Nearest : " + nearest);
Console.WriteLine("Always down: " + alwaysDown);
Console.WriteLine("Always up : " + alwaysUp);
// To hundreds of dollars
nearest = 100 * Math.Round(amount / 100);
alwaysDown = 100 * Math.Floor(amount / 100);
alwaysUp = 100 * Math.Ceiling(amount / 100);
Console.WriteLine();
Console.WriteLine("To hundreds of dollars");
Console.WriteLine("----------------------");
Console.WriteLine("Nearest : " + nearest);
Console.WriteLine("Always down: " + alwaysDown);
Console.WriteLine("Always up : " + alwaysUp);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Of course, you can also display rounded values with cents , if you want, using - value.ToString("N2").
Value-Added Tax
In Europe, we have a nice thing called value-added tax (VAT ). Everybody is happy to pay more money for goods if it allows politicians to have a bigger budget for ... Actually, what for?
Task
In this task, you will create a simple VAT calculator (see Figure 10-8). The program starts from the price a customer pays for a product and calculates the price without VAT (the merchant gets from the purchase) and also the VAT itself (what the merchant transfers to the tax administrator).
Figure 10-8 Calculating VAT
Analysis
If you want to program something, you have to understand the essence of that something first. So, how does the European VAT work?
The foundation of the calculation is the price without VAT. To get this price, the appropriate percent part (for example, 21 percent) is added, and you get the price a customer pays. What is important is that the percents are calculated from the price without VAT, not from the customer price (see Figure 10-9)!
Figure 10-9 Understanding how the VAT works
If the VAT rate is, for example, 21 percent, you need to divide the customer price by 1.21 to get the price without the VAT. For the general value of the tax rate, you calculate the divisor by adding the appropriate fraction to 1.
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter customer price of a product: ");
string inputPrice = Console.ReadLine();
double customerPrice = Convert.ToDouble(inputPrice);
Console.Write("Enter VAT rate in %: ");
string inputVatRate = Console.ReadLine();
double vatRate = Convert.ToDouble(inputVatRate);
// Calculations
double divisor = 1 + vatRate / 100.0;
double calculatedPriceWithoutVat = customerPrice / divisor;
double priceWithoutVat = Math.Round(calculatedPriceWithoutVat, 2);
double vat = customerPrice - priceWithoutVat;
// Outputs
Console.WriteLine();
Console.WriteLine("Price without VAT: " + priceWithoutVat.ToString("N2"));
Console.WriteLine("VAT: " + vat.ToString("N2"));
// Waiting for Enter
Console.ReadLine();
}
Summary
In this chapter, you practiced calculations on a variety of real examples from the economic world. What is always the most important in calculations like these is to understand the real-world problem first. To understand how you would get the results without a program, start with a pencil, paper, and a calculator. It is also often helpful to structure your program appropriately, dividing the whole calculation into small pieces, and to use descriptive names for your variables.
Among other things, you learned how to do rounding. Specifically, you studied several built-in mathematical functions.
You know how to use Math.Round for the most common rounding, in other words, to the nearest whole number. You can specify the number of required decimal places in the second parameter of the method call.
You know how to use Math.Floor for always rounding down, in other words, to the greatest integer that is less than or equal to the number being rounded.
You know how to use Math.Ceiling for always rounding up, in other words, to the lowest integer that is greater than or equal to the number being rounded.
You also learned a trick of how to round to hundreds, including dividing by 100 before rounding and multiplying by the same amount afterward.