 # Help with float numbers

Hi All. I have this bit of code

float myNumber = (((5 * 64) + (5 * 8) + 1) / 16); Serial.println (myNumber);

what am I not seeing here. The value printed is 22.00 why am I not seeing 22.5625 as I would expect? This is odd to me.

Put in some decimal points in the constants, and see what happens.

As AWOL said: "Put in some decimal points in the constants, and see what happens."

The key here is that the compiler is kind of stupid. It sees the right hand side of the expression as separate from where the result value is to be assigned. Thus, when the expression contains integer values, it assumes integer operations.

Integer division is of course different from floating point division.

``````float x=3/2;    // 1
float y=((float) 3)/2; // 1.5
float z=3.0/2  // 1.5
``````

For 'x', the right-hand-side is an integer expression, and the result is 1 (with remainder 1, which you get doing the modulo operation).

For 'y' we explicitly cast 3 to (float). When at least one of the elements in a mathemathical expression is float, the compiler decides that the floating point version of division must be used, and also identifies that the result is float.

For 'z', instead of type casting, we just modify the number 3 to 3.0, which is a float. Same result.

You can't multiply sunglasses by 5.

aarg: You can't multiply sunglasses by 5.

Having the entire forehead covered in sunglasses would look stupid.

Rupert909:
Having the entire forehead covered in sunglasses would look stupid.

Funny…

Try to avoid floats altogether if you can. Workarounds with integer math are so much more efficient on an arduino.

Rupert909: Having the entire forehead covered in sunglasses would look stupid.

You are not old enough to know about Hobo Kelly.

KeithRB: You are not old enough to know about Hobo Kelly.

Either that, or not being American.

Even more specific, raised in Southern California since it was a local show.