Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Decimal constants in C#
The decimal type in C# provides built-in constants to retrieve the minimum and maximum possible values for decimal numbers. These constants are useful for validation, range checking, and initialization purposes.
Syntax
Following is the syntax for declaring a decimal constant −
decimal variableName = value M;
Following is the syntax for accessing decimal constants −
decimal.MaxValue // Maximum possible decimal value decimal.MinValue // Minimum possible decimal value
Decimal Constants
The decimal type provides two important constants −
-
decimal.MaxValue− Returns the largest possible decimal value -
decimal.MinValue− Returns the smallest possible decimal value
Example
using System;
class Demo {
static void Main() {
decimal d = 5.8M;
Console.WriteLine("Decimal value: " + d);
Console.WriteLine("Maximum Value: " + decimal.MaxValue);
Console.WriteLine("Minimum Value: " + decimal.MinValue);
}
}
The output of the above code is −
Decimal value: 5.8 Maximum Value: 79228162514264337593543950335 Minimum Value: -79228162514264337593543950335
Using Decimal Constants for Validation
Example
using System;
class ValidationDemo {
static void Main() {
decimal value1 = 1000000.50M;
decimal value2 = decimal.MaxValue;
Console.WriteLine("Value1: " + value1);
Console.WriteLine("Is value1 within decimal range? " + IsValidDecimal(value1));
Console.WriteLine("Value2: " + value2);
Console.WriteLine("Is value2 at maximum? " + (value2 == decimal.MaxValue));
// Demonstrating range check
Console.WriteLine("Decimal range spans from " + decimal.MinValue + " to " + decimal.MaxValue);
}
static bool IsValidDecimal(decimal value) {
return value >= decimal.MinValue && value <= decimal.MaxValue;
}
}
The output of the above code is −
Value1: 1000000.50 Is value1 within decimal range? True Value2: 79228162514264337593543950335 Is value2 at maximum? True Decimal range spans from -79228162514264337593543950335 to 79228162514264337593543950335
Conclusion
The decimal.MaxValue and decimal.MinValue constants provide access to the extreme values of the decimal type range. These constants are particularly useful for validation, initialization, and boundary checking in financial and precision-critical applications where decimal types are commonly used.
