c sharp

How to Convert Double to Integer in C#

C# a popular object-oriented programming language is used a lot in creating games, websites, and other software. One common task that you may need to perform in C# is converting a double to an integer, this article will explore how to convert a double to an integer in C#.

Converting Double to Integer in C#

In C#, the double data type is a floating-point type that represents a double-precision 64-bit number (8 bytes). On the other hand, the int data type is an integer type representing a 32-bit signed integer. Converting a double to an integer in C# can be done using:

Method 1: Convert.ToInt32() Method

The Convert.ToInt32() method is a built-in C# method that can be used to convert a double to an integer, here is an example code that demonstrates the use of the Convert.ToInt32() method:

using System;

class Program {

  static void Main(string[] args) {

     double number = 10.5;

     int integerNumber = Convert.ToInt32(number);

     Console.WriteLine("Double Number: " + number);

     Console.WriteLine("Integer Number: " + integerNumber);

  }

}

In the above code, we first declare a double variable called “number” with a value of 10.5. We then use the Convert.ToInt32() method to convert the double to an integer and assign the result to the “integerNumber” variable. Finally, we output the original double value and the converted integer value to the console:

Method 2: Casting the Double to an Integer

Another way to convert a double to an integer in C# is by casting the double to an integer, here is an example code that demonstrates this method:

using System;

class Program {

  static void Main(string[] args) {

    double number = 10.5;

    int integerNumber = (int)number;

    Console.WriteLine("Double Number: " + number);

    Console.WriteLine("Integer Number: " + integerNumber);

  }

}

Here in the above code, we first declare a double variable called “number” with a value of 10.5. We then cast the double to an integer using the (int) operator and assign the result to the “integerNumber” variable. Finally, we output the original double value and the converted integer value to the console.

Text Description automatically generated

Conclusion

Converting a double to an integer is a common task in C# as we have seen in this article, there are two methods for achieving this: using the Convert.ToInt32() method and casting the double to an integer. By following the examples and steps outlined in this article, you should now have a good understanding of how to convert a double to an integer in C#.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.