Parsing Numbers
Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 4 of 20.
Every word in args is a string, so "12.50" must be turned into a number before you can add or format it. decimal.Parse(text) does that and throws an exception when the text is not a number. decimal.TryParse returns false instead and hands the number back through an out variable.
Parsing also depends on the computer's culture. On a computer set to German, decimal.Parse("12.50") returns 1250, because a dot separates thousands there. Pass CultureInfo.InvariantCulture (from System.Globalization) and a dot is always the decimal point:
using System.Globalization;
if (decimal.TryParse("3.75", CultureInfo.InvariantCulture, out var km))
Console.WriteLine($"You ran {km} km");
else
Console.WriteLine("That is not a number");Challenge
Beginneradd still prints the amount as text. Parse it, so the tracker can count with it.
- Add
using System.Globalization;as the first line ofProgram.cs. - In the
addcase, parseargs[2]withdecimal.TryParseandCultureInfo.InvariantCultureintoamount. - When it fails, print
Invalid amount:and the text, and leave the case withbreak;.dotnet run -- add Lunch abcprintsInvalid amount: abcand nothing else. - Otherwise print the parsed amount with two decimals.
dotnet run -- add Lunch 12.5printsAdded Lunch: 12.50, andadd Bus 3printsAdded Bus: 3.00.
Try it: the terminal beside the editor already reads dotnet run -- add Lunch 12.5, so press Run: Added Lunch: 12.50. Change 12.5 to abc and Run again: Invalid amount: abc, and no crash.
Try it yourself
var count = 0;
var total = 0m;
if (args.Length == 0)
{
Console.WriteLine("Expense Tracker");
Console.WriteLine($"{count} expenses");
Console.WriteLine($"Total: {total:F2}");
}
else
{
switch (args[0])
{
case "add":
Console.WriteLine($"Added {args[1]}: {args[2]}");
break;
default:
Console.WriteLine($"Unknown command: {args[0]}");
break;
}
}