Menu
CoddyTech

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 icon

Challenge

Beginner

add still prints the amount as text. Parse it, so the tracker can count with it.

  1. Add using System.Globalization; as the first line of Program.cs.
  2. In the add case, parse args[2] with decimal.TryParse and CultureInfo.InvariantCulture into amount.
  3. When it fails, print Invalid amount: and the text, and leave the case with break;. dotnet run -- add Lunch abc prints Invalid amount: abc and nothing else.
  4. Otherwise print the parsed amount with two decimals. dotnet run -- add Lunch 12.5 prints Added Lunch: 12.50, and add Bus 3 prints Added 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;
    }
}

All lessons in C# and .NET Basics