Skip to Content
Course content

114: The Math Class and Numeric Types

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of handling numbers in C# like working in a high-end carpentry shop. You don't just have one "measuring tool." You have a rough tape measure for quick estimates, a precision caliper for engine parts, and a specialized jig for perfect 45-degree cuts. If you try to measure a microscopic screw with a chunky construction tape measure, you're going to have a bad time. The same thing happens in code; if you pick the wrong numeric type or try to do manual math when a specialized tool exists, you'll end up with "rounding drift" that can crash a program or lose a company money.

In C#, the "measuring tools" are your numeric types (like int, double, and decimal), and the "specialized jigs" are the static methods found in the System.Math class.

Picking the Right Tool for the Job

I see a lot of developers default to double for everything. I'll tell you right now: don't do that. A double is a "floating-point" number. It's incredibly fast and can handle massive ranges, but it's not perfectly precise. It's great for physics engines or scientific simulations where a tiny fraction of a difference doesn't matter.

But if you're dealing with money, use decimal. Period. The decimal type is slower, but it's designed for financial calculations where 0.1 + 0.2 must equal exactly 0.3. If you use double for a shopping cart, you'll eventually find a penny missing from your totals because of how binary floating-point math works under the hood.


double physicsDistance = 1234.56789; // Great for coordinates
decimal productPrice = 19.99m;        // The 'm' suffix tells C# this is a decimal
int itemQuantity = 5;               // Whole numbers only

Cleaning Up the Mess

In the real world, math is messy. You'll often end up with a number like 14.333333335, but your UI only has room for two decimal places. This is where the Math class comes in. It's a "static class," meaning you don't need to create an object to use it; you just call Math.MethodName().

You have three main ways to "trim" your numbers. Math.Round is the most common, but be careful—by default, it uses "Banker's Rounding" (rounding to the nearest even number). If you want the rounding you learned in grade school, you'll need to specify a MidpointRounding mode.


double rawValue = 12.5;

double rounded = Math.Round(rawValue, 0); // Might be 12 or 13 depending on the mode
double ceiling = Math.Ceiling(rawValue);  // Always goes UP to 13
double floor = Math.Floor(rawValue);      // Always goes DOWN to 12

I usually reach for Math.Ceiling when calculating pagination. If you have 51 items and 10 items per page, 51/10 is 5.1. You can't have 5.1 pages, and 5 pages would leave one item behind, so you "ceiling" it up to 6 pages.

The Heavy Lifters

Finally, there are the methods that save you from writing complex loops or importing huge libraries. Instead of multiplying a number by itself five times, use Math.Pow. Instead of guessing the side of a square from its area, use Math.Sqrt.

One of my favorites for game logic or UI layout is Math.Clamp (introduced in newer versions of .NET). It forces a number to stay between a minimum and a maximum value. It's way cleaner than writing a bunch of if statements to make sure a player's health doesn't go above 100 or below 0.


// Calculate the hypotenuse of a triangle (a^2 + b^2 = c^2)
double sideA = 3.0;
double sideB = 4.0;
double hypotenuse = Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideB, 2));

// Keep a volume slider between 0 and 100
int userSetting = 150; 
int finalVolume = Math.Clamp(userSetting, 0, 100); // Result: 100



📋 Practical Task

Build a Precision Currency Converter

You are building a currency converter for a travel app. You need to handle a conversion where the exchange rate results in many decimal places, but the final output must be formatted for a bank statement.

Requirements:

  • Create a decimal variable for the amountInUSD (e.g., 100.50).
  • Create a decimal variable for the exchangeRate (e.g., 0.923456).
  • Calculate the totalInEUR by multiplying the two.
  • Use Math.Round to round the final EUR result to exactly 2 decimal places using MidpointRounding.AwayFromZero (this ensures .005 rounds UP to .01).
  • Print the raw result and the rounded result to the console to see the difference.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.