- Home /
How can I round a number?
My fallDamage gets returned as something like 10.2367844 depending on distance.
How can I round this up or down in script?
I could just say if var > 1 but < 2 = 1, but I'd have to do that right the way through to 100.
Is there an easier way?
Answer by Statement · Jan 13, 2011 at 12:14 PM
Use Mathf.Round, Mathf.Ceil, Mathf.Floor, or cast them to ints:
int asInt = (int)floatValue;
For your example, you want to use Mathf.Floor or int casting, depending on your needs. Mathf.Floor return a float value. Casting returns of course an int value. Both approaches will get rid of any decimals.
well i didn't think it would be that simple :D thanx
Be also sure to check out Borgo's reference to $$anonymous$$athf.FloorToInt.
Answer by Borgo · Jan 13, 2011 at 12:19 PM
You can use .Net functions in your scripts, take a look at Round function documentation:
http://msdn.microsoft.com/en-us/library/system.math.round(v=vs.71).aspx
Take a look at Mathf functions too:
http://unity3d.com/support/documentation/ScriptReference/Mathf.html
http://unity3d.com/support/documentation/ScriptReference/Mathf.FloorToInt.html
Example:
// Prints 10
Debug.Log(Mathf.FloorToInt(10.7));
Yes, but these does not operate on float, which is a common type in game program$$anonymous$$g. You'd have to cast to decimal or double for every operation and it's a quite time consu$$anonymous$$g task.
Your answer

Follow this Question
Related Questions
"bleeding" when using configurable joints 2 Answers
Math Round? 2 Answers
Is it possible to round down 0.99 to 0? 2 Answers
Math.round not work 1 Answer
Rounding to multiples of 0.5 1 Answer