println() bug?

I was running some println statements for debugging and couldn't find out what was wrong with my code.
In the end I cut it right back to the following sketch and saw the problem was with println().

The sketch should print out 4038021375 but instead prints out "4038021376.00"!

Any clues anyone?

(Arduino 1.0.1)

double a = 4038021375;

void setup()
{
  delay(2000);
  Serial.begin(9600);
  Serial.println(a);
} 

void loop()
{
}

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

On the Arduino double is the same as float, and float has 6-7 decimal digits of precision. You have hit the precision limit.

Thanks Nick,

I initialised the double with a certain thirty two bit pattern that I wanted (B11110000101011110101000011111111) assuming that you could use all the bits like an integer and not worrying about the decimal value. As long as you don't exceed the number of bits in the variable and watch the twos complement you can't go wrong........... not!

A lesson learnt.

If you want a 32 bit bit-pattern, use a 32 bit integer type, like "unsigned long", or "uint32".

On some architectures, "double" may be 64 bits.

the print() and println() functions print floating point numbers to 2 dp by default. This means that even if the float is a whole number you will get two numbers following the decimal point.
If you did this for example:

double a = 4038021375;

void setup()
{
  delay(2000);
  Serial.begin(9600);
  Serial.println(a,0);
} 

void loop()
{
}

Or this:

double a = 4038021375;

void setup()
{
  delay(2000);
  Serial.begin(9600);
  Serial.println((long)a);
} 

void loop()
{
}

You wouldn't see the decimal.

Have a look at

[b]union[/b] {
 float f;
 long i;
} bitpattern;

bitpattern.i = 0x4010000;

Serial.println( bitpattern.f);

Hmm... cast-through-union cool! :slight_smile: