0
0
C Sharp (C#)programming~5 mins

Floating point types (float, double, decimal) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Floating point types let you store numbers with decimals. They help when you need to work with fractions or very precise values.

When you want to store prices or money values accurately.
When you need to calculate measurements like height or weight with decimals.
When you want to work with scientific data that requires decimals.
When you need to store very large or very small decimal numbers.
When you want to do math with fractions, like 3.14 or 0.001.
Syntax
C Sharp (C#)
float myFloat = 3.14f;
double myDouble = 3.14;
decimal myDecimal = 3.14m;

Use f after a number to tell C# it is a float.

Use m after a number to tell C# it is a decimal.

Examples
This stores a temperature value as a float. The f is needed.
C Sharp (C#)
float temperature = 36.6f;
This stores a distance as a double. No suffix needed because double is default for decimals.
C Sharp (C#)
double distance = 12345.6789;
This stores a price as a decimal. The m suffix is required for decimals.
C Sharp (C#)
decimal price = 19.99m;
Sample Program

This program shows how to declare and print float, double, and decimal values.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        float myFloat = 3.14f;
        double myDouble = 3.14;
        decimal myDecimal = 3.14m;

        Console.WriteLine($"Float value: {myFloat}");
        Console.WriteLine($"Double value: {myDouble}");
        Console.WriteLine($"Decimal value: {myDecimal}");
    }
}
OutputSuccess
Important Notes

Float uses 4 bytes and is less precise.

Double uses 8 bytes and is more precise than float.

Decimal uses 16 bytes and is best for money because it is very precise.

Summary

Float, double, and decimal store numbers with decimals.

Use f for float and m for decimal when writing numbers.

Decimal is best for money, double for general decimals, float for less precise decimals.