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

C#CastingFloating Point

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

You can just do a cast

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

or

decimal val3 = 3;
float val4 = (float)val3;

Solution 2 - C#

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;

Solution 3 - C#

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

Solution 4 - C#

It is just:

float f = (float)6;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaredView Question on Stackoverflow
Solution 1 - C#heavydView Answer on Stackoverflow
Solution 2 - C#Chris PietschmannView Answer on Stackoverflow
Solution 3 - C#Dave the TrollView Answer on Stackoverflow
Solution 4 - C#nedludView Answer on Stackoverflow