Resticing variables to whole numbers

Is there any way to make a variable retain its float status while restricting it to whole numbers? I need my variables to be floats but they should also be whole numbers.

3 Answers

3

Well, the best way to restrict variables to "whole numbers" aka "integers" is by using the "int" parameter type.

Then, if for some reason you really need a float, you probably don't even have to cast to float because casting int to float is not losing precision so it should be an automatic cast ... and I guess UnityScript/JavaScript is pretty loose on these things anyways.

So I guess you can go with:

var myWholeNumberVariable : int;

Normally you'd use a cast to convert between a float and int. So you'd define your variable as a float, but when you need the value as an int youd cast it e.g. x = 5 + (int)myFloat;

There are other methods depending upon your needs to manage the conversions, such as ceiling() or floor(),

Assuming MyNumber is a float, you could do something like this after MyNumber has been assigned a value:

MyNumber = ceil(MyNumber)-1;

I don't know if that syntax is 100% correct and I don't know if what would happen if MyNumber = 4.0000000 before you use ceil. I haven't used this function before.