unity int to float

Unity: Converting int to float

To convert an int (integer) to a float in Unity, there are two different approaches: casting or using the Convert class.

Int to float with cast

The simplest way to convert an int to float is to use a cast:

int number = 5;
float floatNumber = (float)number;

Int to float with Convert

Another method involves using the Convert class:

using System;

int number = 5;
float floatNumber = Convert.ToSingle(number);

It is also possible to perform the reverse operation: float to int.

Division with 2 ints

Be cautious when dividing two integers; even if you specify the return type as float, the calculation won’t consider decimal numbers.

For precise calculations, cast at least one of the two integers:

int number = 5;
int otherNumber = 2;

float calc = number / otherNumber; // equal to 2

float calcWithCast = (float)number / otherNumber; // equal to 2.5

We hope this quick tutorial has been helpful.
Now you know how to convert int to float in Unity.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *