The problem when convert float to int (86927)

using UnityEngine;
using System.Collections;

public class Math : MonoBehaviour {
	int value = 10;
	float ratio1 = 1.1f;
	float ratio2 = 1.2f;
	float ratio3 = 1.3f;

	void Start () {
		Debug.Log (value * ratio1);
		Debug.Log (value * ratio2);
		Debug.Log (value * ratio3);

		Debug.Log ((int)(value * ratio1));
		Debug.Log ((int)(value * ratio2));
		Debug.Log ((int)(value * ratio3));
	}
}

I expect the result will be:
11
12
13
11
12
13

However, the actual result is:
11
12
13
11
12
12

How can I fix the problem?

Use [Mathf.RoundToInt()][1]: Debug.Log(Mathf.RoundToInt(value * ratio1)); [1]: http://docs.unity3d.com/Documentation/ScriptReference/Mathf.RoundToInt.html

By way of explanation, typecasting to int just truncates off the decimals. If you want to round to the nearest int you need to use a rounding function.

1 Answer

1

Instead of this…

Debug.Log ((int)(value * ratio1));
Debug.Log ((int)(value * ratio2));
Debug.Log ((int)(value * ratio3));

Try this…

Debug.Log ((value * (int)ratio1));
Debug.Log ((value * (int)ratio2));
Debug.Log ((value * (int)ratio3));

Not sure if it will work, but when I look at your code it is the first thing I would try.