Decimal numbers allow us to represent real numbers, that is, those that can have a fractional part and be positive or negative.
In C#, the main types for storing decimal numbers are float, double, and decimal.
Each has a specific range and precision, which must be considered depending on the type of calculations to be performed.
| C# Type | .NET Type | Bits | Precision | Suffix | When to use it? |
|---|---|---|---|---|---|
float | Single | 32 | ~7 digits | f | 3D Graphics, Unity, ML, Huge Arrays. |
double | Double | 64 | ~15 digits | d | Science, Engineering, general use. |
decimal | Decimal | 128 | ~28 digits | m | Money, Finance, Accounting. |
- Are you calculating money, payroll, prices, or anything where losing a cent is illegal or a problem? Use
decimal. - Are you making a video game, processing audio, or working with neural networks? Use
float. - None of the above (general use, mathematics)? Use
double(it’s the default standard in C#).
Floating Point: float and double
The float and double types are Binary Floating-Point types. They are designed following the IEEE 754 standard, which is the norm followed by almost all modern processors for fast mathematics.
Internally, they do not store the exact number. They store a scientific approximation based on three parts:
- Sign: Positive or negative.
- Mantissa: The significant digits of the number.
- Exponent: Where we place the decimal point (hence “floating point”, the point moves).
This allows representing astronomically large or microscopically small numbers, but at a cost: loss of precision.
float (single precision)
- Size: 32 bits (4 bytes).
- Precision: ~6-9 digits.
- Suffix:
forF. - Use: 3D Graphics (Unity uses
floatfor everything), physics engines, signal processing where speed is critical and a small error is acceptable.
float gravity = 9.81f; // Note the 'f' at the end
double (double precision)
- Size: 64 bits (8 bytes).
- Precision: ~15-17 digits.
- Suffix:
dorD(optional, it’s the default). - Use: Scientific calculations, general mathematics.
double sunDistance = 149_600_000.5; // By default it's double
In C#, any number with decimals you write in the code (literal), like 3.14, is automatically interpreted as double. If you want it to be float, **you have to add the f**.
The High-Precision Solution decimal
If float and double are fast but “imprecise”, decimal is the complete opposite.
The decimal type is a 128-bit Floating-Point type specifically designed for financial and monetary calculations. Unlike its siblings, decimal uses base 10 instead of base 2 for its fractional part.
This means numbers like are represented exactly.
- Size: 128 bits (16 bytes).
- Precision: 28-29 significant digits.
- Suffix:
morM(for “Money”). - Range: Smaller than
double, but much more precise. - Performance: Much slower (calculated by software, not hardware).
decimal price = 19.99m; // The 'm' is MANDATORY
decimal tax = 0.21m;
decimal total = price * (1 + tax); // Exact calculation, without strange rounding errors
If you try to assign a double literal to a decimal without the m suffix, the compiler will give you an error. C# protects you from losing precision unintentionally.
Common Mathematical Operations
Arithmetic operations are similar to those for integers. We can perform addition, subtraction, multiplication, and division with floating-point numbers.
double x = 10.5;
double y = 3.2;
double sum = x + y;
double subtraction = x - y;
double multiplication = x * y;
double division = x / y;
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Subtraction: {subtraction}");
Console.WriteLine($"Multiplication: {multiplication}");
Console.WriteLine($"Division: {division}");
The Math class in C# provides useful methods for performing advanced mathematical operations. We will see it in the next tutorial.
Practical Examples
Compound Interest Calculation
This example calculates compound interest using the decimal type to ensure precision in financial calculations:
decimal principal = 1000.0m; // Initial capital
decimal interestRate = 0.05m; // Annual interest rate (5%)
int years = 10; // Period in years
decimal finalAmount = principal * (decimal)Math.Pow((double)(1 + interestRate), years);
Console.WriteLine($"Final amount after {years} years: {finalAmount:C}");
Temperature Conversion
This example converts a temperature from Celsius to Fahrenheit using the double type:
double celsius = 25.0;
double fahrenheit = (celsius * 9 / 5) + 32;
Console.WriteLine($"{celsius}°C is equal to {fahrenheit}°F");
Mean and Standard Deviation Calculation
As an example of using floating-point numbers, let’s calculate the mean and standard deviation of a list of numbers in C#.
using System;
using System.Linq;
public class Statistics
{
public static void Main()
{
double[] values = { 1.5, 2.3, 3.1, 4.7, 5.8 };
double mean = values.Average();
double sumOfSquares = values.Select(val => Math.Pow(val - mean, 2)).Sum();
double standardDeviation = Math.Sqrt(sumOfSquares / values.Length);
Console.WriteLine($"Mean: {mean}");
Console.WriteLine($"Standard Deviation: {standardDeviation}");
}
}
In this example:
- We use
Average()to calculate the mean of the values. - We calculate the standard deviation using
Math.PowandMath.Sqrt, functions from theMathlibrary.
