Why are my float rounding themselves out to the lowest int without me coding it out?
Float rounds itself to the lowest int without me coding it, as seen in the Console and Inspector.
public float test;
void Update()
{
test = 150 / 100;
Debug.Log(test);
}
I have had the problem happen on my main project but I replicated it in a fresh project.
Answer by IggyZuk · Oct 13, 2020 at 02:14 PM
Try adding an f at the end.
150f / 100f
Thanks! I thought the f was only for numbers with decimals.
Yes, it is for numbers with decimals. It defines a literal value of type float instead of "int". What you're doing in your original code is an integer division because both operands are of type integer. So int / int
results in an int
. It doesn't matter where or how you use this expression. So it doesn't matter that you assigned the expression to a float variable. The actual division will be an integer division. As soon as one of the operands is a float you will actually perform a floating point division.
You can add a decimal if you want: 150.0f/100.0f. But the f by itself takes care of it. 150.0 (with no f) is a different error. 150.0 is like a 64-bit number, where floats like 150.0f are only 32.
Your answer
Follow this Question
Related Questions
ToString ("f0") is rounding my float 1 Answer
Adding a int and a float? 2 Answers
Optimization Question - Floats or Ints? 0 Answers
Color float rgb values cannot be converted correctly to int, and hex. 1 Answer
Int not getting rounded data 0 Answers