- Home /
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.
Answer by jashan · Aug 09, 2010 at 02:37 PM
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;
Answer by Noise crime · Aug 09, 2010 at 02:53 PM
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(),
Answer by Ares · Aug 09, 2010 at 06:33 PM
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.
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
print to only two decimal places. 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Maths with variables 2 Answers
Acces to a var from another Script. 2 Answers