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
Convert Decimal to the equivalent 64-bit unsigned integer in C#
To convert the value of a Decimal to the equivalent 64-bit unsigned integer (ulong), C# provides the Decimal.ToUInt64() method. This method truncates the decimal portion and returns only the integer part as a ulong value.
Syntax
Following is the syntax for converting a decimal to 64-bit unsigned integer −
ulong result = Decimal.ToUInt64(decimalValue);
Parameters
decimalValue − A
Decimalnumber to be converted to a 64-bit unsigned integer.
Return Value
Returns a ulong value equivalent to the decimal value, with the fractional part truncated (not rounded).
Using Decimal.ToUInt64() with Fractional Values
When converting decimals with fractional parts, the method truncates (cuts off) the decimal portion −
using System;
public class Demo {
public static void Main() {
Decimal val = 99.29m;
Console.WriteLine("Decimal value = " + val);
ulong res = Decimal.ToUInt64(val);
Console.WriteLine("64-bit unsigned integer = " + res);
}
}
The output of the above code is −
Decimal value = 99.29 64-bit unsigned integer = 99
Using Decimal.ToUInt64() with Small Decimal Values
Values less than 1 will result in 0 when converted to unsigned integer −
using System;
public class Demo {
public static void Main() {
Decimal val = 0.001m;
Console.WriteLine("Decimal value = " + val);
ulong res = Decimal.ToUInt64(val);
Console.WriteLine("64-bit unsigned integer = " + res);
}
}
The output of the above code is −
Decimal value = 0.001 64-bit unsigned integer = 0
Using Decimal.ToUInt64() with Large Values
The method handles large decimal values within the ulong range −
using System;
public class Demo {
public static void Main() {
Decimal val1 = 18446744073709551615m; // Max ulong value
Decimal val2 = 1234567890123.456m;
Console.WriteLine("Decimal value 1 = " + val1);
ulong res1 = Decimal.ToUInt64(val1);
Console.WriteLine("64-bit unsigned integer 1 = " + res1);
Console.WriteLine("\nDecimal value 2 = " + val2);
ulong res2 = Decimal.ToUInt64(val2);
Console.WriteLine("64-bit unsigned integer 2 = " + res2);
}
}
The output of the above code is −
Decimal value 1 = 18446744073709551615 64-bit unsigned integer 1 = 18446744073709551615 Decimal value 2 = 1234567890123.456 64-bit unsigned integer 2 = 1234567890123
Key Rules
The fractional part is truncated, not rounded.
Values must be within the
ulongrange (0 to 18,446,744,073,709,551,615).Negative decimal values will throw an
OverflowException.Values greater than
ulong.MaxValuewill throw anOverflowException.
Conclusion
The Decimal.ToUInt64() method converts decimal values to 64-bit unsigned integers by truncating the fractional part. This method is useful when you need to extract only the whole number portion of a decimal value as a ulong type.
