Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert Int/Decimal to float in C#?

How does one convert from an int or a decimal to a float in C#?

I need to use a float for a third-party control, but I don't use them in my code, and I'm not sure how to end up with a float.

like image 269
Jared Avatar asked Jun 25 '09 03:06

Jared


People also ask

Can we use %d for float in c?

So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that! %. 2f means that the variable to be printed will be of type float and '.

Can you go from int to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.

Is int and float equal in c?

Casting the int to a float explicitly will do absolutely nothing. The int will be promoted to a float for purposes of comparison anyway.


2 Answers

You can just do a cast

int val1 = 1; float val2 = (float)val1; 

or

decimal val3 = 3; float val4 = (float)val3; 
like image 195
heavyd Avatar answered Oct 06 '22 09:10

heavyd


The same as an int:

float f = 6; 

Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:

int i = 8; float f = Convert.ToSingle(i); 

Or you can just cast an int to a float:

float f = (float)i; 
like image 34
Chris Pietschmann Avatar answered Oct 06 '22 08:10

Chris Pietschmann