In this example, we’ll learn how to create a simple tax calculator using Class in C# Console Application.
You will learn how to get input from a user and do some calculations on that input. By the end of this tutorial, you will be able to run your tax calculator to calculate the grand total of an item given a specific tax rate.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cce_console { public class TaxCalculator { private static decimal _itemPrice; private static decimal _percentTaxRate; private static decimal _totalPrice; public TaxCalculator(string inputItemPrice, string inputTaxRate) { _itemPrice = Decimal.Parse(inputItemPrice); _percentTaxRate = Decimal.Parse(inputTaxRate) / 100; } public void CalculateTotalPrice() { _totalPrice = _itemPrice + (_itemPrice * _percentTaxRate); } public void GetTotalMsg() { Console.WriteLine("The subtotal is {0:C} and the total price is {1:C} at the tax rate of {2:p0}", _itemPrice, _totalPrice, _percentTaxRate); } } class Program { static void Main(string[] args) { Console.Write("Enter Price of item: "); string itemPrice = Console.ReadLine(); Console.Write("Enter tax rate (in percentage): "); string taxRate = Console.ReadLine(); TaxCalculator myTaxCalculator = new TaxCalculator(itemPrice, taxRate); myTaxCalculator.CalculateTotalPrice(); myTaxCalculator.GetTotalMsg(); Console.ReadKey(); } } } |
Output: