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
Implicit conversion from 64-bit signed integer (long) to Decimal in C#
The long type represents a 64-bit signed integer in C#. C# allows implicit conversion from long to decimal because no data loss occurs during this conversion. The decimal type can accommodate all possible long values while providing higher precision.
Syntax
Following is the syntax for implicit conversion from long to decimal −
long longValue = 123456789; decimal decimalValue = longValue; // Implicit conversion
How It Works
The conversion happens automatically because the decimal type has a wider range and higher precision than long. The decimal type can represent all integer values that long can hold, plus fractional values with up to 28-29 significant digits.
Example
using System;
public class Demo {
public static void Main() {
long val = 76755565656565;
decimal dec;
Console.WriteLine("Implicit conversion from 64-bit signed integer (long) to Decimal");
dec = val;
Console.WriteLine("Decimal : " + dec);
}
}
The output of the above code is −
Implicit conversion from 64-bit signed integer (long) to Decimal Decimal : 76755565656565
Using Maximum Long Value
Example
using System;
public class Program {
public static void Main() {
long maxLong = long.MaxValue;
long minLong = long.MinValue;
decimal maxDecimal = maxLong; // Implicit conversion
decimal minDecimal = minLong; // Implicit conversion
Console.WriteLine("Max long value: " + maxLong);
Console.WriteLine("Converted to decimal: " + maxDecimal);
Console.WriteLine("Min long value: " + minLong);
Console.WriteLine("Converted to decimal: " + minDecimal);
}
}
The output of the above code is −
Max long value: 9223372036854775807 Converted to decimal: 9223372036854775807 Min long value: -9223372036854775808 Converted to decimal: -9223372036854775808
Key Rules
-
The conversion from
longtodecimalis implicit ? no cast operator is required. -
No data loss occurs during this conversion because decimal can represent all long values.
-
The decimal type provides higher precision and can handle fractional values, unlike long.
-
This conversion is part of C#'s predefined implicit numeric conversions.
Conclusion
C# allows implicit conversion from long to decimal because the decimal type can safely represent all long values without data loss. This conversion happens automatically and is useful when you need to perform decimal arithmetic with integer values.
