Strange rounding errors with doubles

Hello,

I am trying to do some simple math, for example

double test=456/100;
Serial.println(test);

But the result I am getting is 4.00, instead of the expected 4.56. If I declare a variable

double test=4.56

The digits past the decimal point are kept, but for any other calculation with doubles or floats the number is rounded to the nearest 1.

Is there a simple fix that I should apply? Is there something I am doing wrong?

Thanks in advance.

I think its because you are trying to divide to integer values, which gives an integer; you need to cast one or both of them to doubles (technically, on the Arduino, a double is a float, though) before division, to return a double (float). See:

http://arduino.cc/en/Reference/Float

:slight_smile:

double test=456/100;

I play the compiler.
456 is a int
100 is a int
456/100 is therefor an int ==> 4 (implicit rounding down)
assign this int to a double named test => 4.00
print it. ==> 4.00

Is there a simple fix that I should apply? Is there something I am doing wrong?

Try this
double test = ((double)456) / 100;
or
double test=456/100.0; divide explicit by a float/double (same on arduino)

Thanks!

I figured it was something like that, I just had the casting in the wrong place.