- Home /
C# divide float by integer
Hello, I need to divide a float by and integer. I have tried casting but nothing seems to work. I would like to see .25 as my result in the following problem.
0.5/2 = .25
Here is some examples of what I have tried that doesnt work and the result it gave. 0.5/((float)2) = 0 0.5/2.0 = 0 ((float).5)/((float) 2) = 0 (float).5/ 2 = 0
Thanks in advance!
Exactly how are you testing it? Because `Debug.Log(0.5/2.0);` correctly says 0.25, and `float x=0.5/2.0;` prints nothing -- it gives an error (double to float.)
Not a single one of the things you wrote should ever give 0.
I was looking at it in the watch section in the debug mode in $$anonymous$$ono. It doesn't seem to work very well. The answers provided by Jordan and Eric5h5 are both correct ways to do this.
Answer by Landern · Dec 06, 2012 at 09:07 PM
//c#
float result = 0.5f / 2;
//js
var result : float = 0.5f / 2;
Answer by Eric5h5 · Dec 06, 2012 at 09:09 PM
That's how it works by default. As long as one of the numbers involved in an operation is floating point, then the result is floating point and you don't have to do anything special.
void Start () {
Debug.Log (0.5f/2); // result is .25
}
This is an old answer, but as it lacks certain details, I'll add it as a comment. There are 2 rules within the operation flow that are to be taken into consideration.
Brackets rules above everything else.
Additions & Subtractions are isolators, like brackets.
What this means is that having only integers between brackets or Addition/Subtraction will results in integers-based values for those sub-operation.
(Int_A / Int_B) + Float_C x (Int_D / Float_E) is an formula that works to display the isolators effect. (Note that "x" is used for multiplication. It would be a italic text code otherwise.)
(Int_A / Int_B) will return the floored value as an integer.
(Int_D / Float_E) will return the proper float value as the float and integer are isolated together.
Float_C will be multiplied by the float result of (Int_D / Float_E).
So, if we fill the numbers like ( (int)1 / (int)2 ) + (float)3 x ( (int)4 / (float)5 ), the result will be 2.4f while, on paper, it should be 2.9f. That's because the ( (int)1 / (int)2 ) returns 0 and not 0.5f due to the isolating brackets being prioritized before the conversion to a float.
Changing the formula to ( (int)1 / (int)2 ) x (float)3 x ( (int)4 / (float)5 ) will result with 0.