Convert string read from console to numbers - CSharp Language Basics

CSharp examples for Language Basics:Console

Description

Convert string read from console to numbers

Demo Code

using static System.Console;
class Program// ww w .j a v a  2 s .c o m
{
   static decimal SalesTax(decimal amount, string twoLetterRegionCode)
   {
      decimal rate = 0.0M;
      switch (twoLetterRegionCode)
      {
         case "CH": // Switzerland
             rate = 0.08M;
             break;
         case "DK": // Denmark
         case "NO": // Norway
             rate = 0.25M;
             break;
         case "CA": // California
         rate = 0.0825M;
         break;
         default: // most US states
         rate = 0.06M;
         break;
      }
      return amount * rate;
   }
   static void Main(string[] args)
   {
      string amountInText = "123123123123123";
      Write("Enter a two letter region code: ");
      string region = ReadLine();
      if (decimal.TryParse(amountInText, out decimal amount))
      {
         decimal taxToPay = SalesTax(amount, region);
         WriteLine($"You must pay {taxToPay} in sales tax.");
      }
      else
      {
         WriteLine("You did not enter a valid amount!");
      }
   }
}

Related Tutorials