ConvertDecimal to equivalent 32-bit unsigned integer in C#

To convert the value of the specified decimal to the equivalent 32-bit unsigned integer, C# provides the Decimal.ToUInt32() method. This method truncates the fractional part and returns only the whole number portion as a uint value.

Syntax

Following is the syntax for converting decimal to uint −

public static uint ToUInt32(decimal value);

Parameters

  • value − The decimal number to be converted to a 32-bit unsigned integer.

Return Value

Returns a 32-bit unsigned integer (uint) equivalent to the specified decimal value. The fractional part is truncated, not rounded.

Using Decimal.ToUInt32() with Small Values

When the decimal value is less than 1, the method returns 0 since the fractional part is truncated −

using System;

public class Demo {
   public static void Main() {
      decimal val = 0.001m;
      Console.WriteLine("Decimal value = " + val);
      uint res = decimal.ToUInt32(val);
      Console.WriteLine("32-bit unsigned integer = " + res);
   }
}

The output of the above code is −

Decimal value = 0.001
32-bit unsigned integer = 0

Using Decimal.ToUInt32() with Larger Values

For decimal values greater than or equal to 1, the method returns the integer part by truncating the decimal portion −

using System;

public class Demo {
   public static void Main() {
      decimal val = 67.487m;
      Console.WriteLine("Decimal value = " + val);
      uint res = decimal.ToUInt32(val);
      Console.WriteLine("32-bit unsigned integer = " + res);
   }
}

The output of the above code is −

Decimal value = 67.487
32-bit unsigned integer = 67

Handling Range and Exception Cases

The method throws an OverflowException if the decimal value is outside the range of uint (0 to 4,294,967,295) −

using System;

public class Demo {
   public static void Main() {
      try {
         decimal validVal = 4294967295m; // Max uint value
         decimal invalidVal = -1m; // Negative value
         
         Console.WriteLine("Valid conversion:");
         uint result1 = decimal.ToUInt32(validVal);
         Console.WriteLine("Result: " + result1);
         
         Console.WriteLine("\nAttempting invalid conversion:");
         uint result2 = decimal.ToUInt32(invalidVal);
      }
      catch (OverflowException ex) {
         Console.WriteLine("OverflowException: " + ex.Message);
      }
   }
}

The output of the above code is −

Valid conversion:
Result: 4294967295

Attempting invalid conversion:
OverflowException: Value was either too large or too small for a UInt32.

Conclusion

The Decimal.ToUInt32() method converts decimal values to 32-bit unsigned integers by truncating the fractional part. It's important to handle potential OverflowException when dealing with values outside the valid uint range (0 to 4,294,967,295).

Updated on: 2026-03-17T07:04:36+05:30

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements