Round up to the nearest pound.
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
(int)xCasts a double to an int, truncating any decimal part. This effectively rounds the number toward zero (so positive doubles are rounded down).
string.Format("{0:F2}", x)Returns the value x formatted according to the format specifier. {0:F2} means “argument 0, fixed-point with 2 decimal places”.
E.g. assuming name = "Dave" and age = 18:
Console.WriteLine(string.Format("Hello {0}. You are {1} years old.", name, age));
outputs Hello Dave. You are 18 years old.. The numbers inside the curly brackets refer to the order of the arguments. You can also use string interpolation: $"Hello {name}. You are {age} years old.".
Questions to think about with this program to check your understanding:
Explain the purpose of using (int) to cast the variable amount from a double to an int.
To round down the number. When casting from one data type to another, data can be lost. We use this to our advantage here because we want to discard the decimal places resulting in the number being rounded down.
Why has the F2 format specifier been used in the output statements?
To make the output two decimal places. F2 stands for fixed-point with 2 decimal digits, so values like 0.6 render as 0.60.
Change the program so that it:
Enter the purchase price: £
3.40
Debit - £4.00
Credit to savings - £0.60
Enter the purchase price: £
3
Debit - £3.00
Credit to savings - £0.00
Enter the purchase price: £
10.23
Debit - £11.00
Credit to savings - £0.77
// Save the change program
using System;
class Submission
{
---
// -------------------------
// Subprograms
// -------------------------
// Return the nearest whole number rounded up
static int nearest_pound(double amount)
{
---
if ((int)amount != amount)
{
---
return (int)amount + 1;
---
}
---
else
{
---
return (int)amount;
---
}
---
}
---
// Return the difference between the number and the rounded number
static double save_the_change(double amount)
{
---
double savings;
if ((int)amount != amount)
{
---
savings = nearest_pound(amount) - amount;
---
}
---
else
{
---
savings = 0;
---
}
---
return savings;
---
}
---
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
---
Console.WriteLine("Enter the purchase price: £");
double purchase_price = Convert.ToDouble(Console.ReadLine());
int debit = nearest_pound(purchase_price);
double savings = save_the_change(purchase_price);
---
Console.WriteLine(string.Format("Debit - £{0:F2}", debit));
Console.WriteLine(string.Format("Credit to savings - £{0:F2}", savings));
---
}
---
}