Silly question - multiplying integers

Hi,

This is a very nooob question … and one I’m a little embarrassed to ask since I’ve been writing code for a few years now. When multiplying an int, it turns the result into a double. However, typecasting back into an int doesn’t seem to work. Why is that the case?

For example:

int score = 5;

score = (int) score * 1.5;

The above code still returns score as a double. How can I multiply an integer by a value and then convert it back to an integer (rounding up / down … don’t really care)?

score = (int)(score * 1.5);
1 Like

There is also Mathf.CeilToInt and Mathf.FloorToInt but I don’t know what the difference is, I guess Mathf.CeilToInt gives the result as int directly?

1 Like

Floor and Ceil return floats whereas FloorToInt and CeilToInt return…well…integers.

Your result is a double because you are multiplying an integer with a double. C# will automatically convert ints to floats to doubles, but the other way around requires an explicit cast.

Remember the order of operations from algebra? C# has something similar. You can see that your cast to int is occurring before the multiplication.

In your original example score = (int) score * 1.5; this is what is happening.

  • Cast int to an int. (No effect)
  • Cast int to double in preparation for multiplication
  • Multiply two doubles
  • Assign that double result to score, which should result in an error since doubles will not automatically get cast to ints.
1 Like

Got it … thanks for the help! Really appreciate it.

The CeilToInt script reference page is a copy and paste of page Ceil, the same with FloorToInt, I knew more or less how it was because of their name “Ceil-To-int”, but you know names can be deceiving some times…

The method signature at the top of the page says static int RoundToInt(float f)