The Maths or the Print Statement?

Hi,

I have been using some integer arithmetic nd noticed, along the way, some unexpected results.

Take the following sketch:

#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);      // maximum for Mega 2560

}

void loop() {
    int val = 123;
    Serial.print("\t|\tInteger: "); Serial.print(val);   Serial.print(" "); 
    Serial.print("\t|\t1 d.p  : "); Serial.print(val,1); Serial.print(" "); 
    Serial.print("\t|\t2 d.p  : "); Serial.print(val,2); Serial.print(" "); 
    Serial.print("\t|\tbin p  : "); Serial.print(val,BIN); Serial.print(" "); 
    while(1);    // wait here forever  
}

The output isn’t what I would have expected.

print(val,1) yields no d.p (would have expected 123.0).
print(val,2) yields what appears to be a binary output (would have expected 123.00).
print(val,BIN) yields the expected binary output.

Is it the maths, the print statement or am I missing something? There is nothing in the Arduino reference for print to suggest this behaviour.

The reason it is important is that I am relying on the print statement to confirm interim values in calculations.

Thanks,
Ric

If the first parameter is an int, then it will be printed as an int, using the second parameter as the number base, which is why your '2 dp' is printed as binary, or base 2. Cast val to a float if you want it printed as a float.

Hi and thanks for replying,

But why does print(val,2) print as 2dp for a float but print as a binary for an int?

Can I take it that the if the number of d.p in the print statement matches the precision of the type, then all will be well?

Ric

ricm: But why does print(val,2) print as 2dp for a float but print as a binary for an int?

The second argument to print for an int is the base to print it in. The second argument to print for a float is the number of digits to print after the decimal point.

ricm: Can I take it that the if the number of d.p in the print statement matches the precision of the type, then all will be well?

Don't understand this.

The second argument to print for an int is the base to print it in. The second argument to print for a float is the number of digits to print after the decimal point.

I now understand exactly. Thank you, Ric

But why does print(val,2) print as 2dp for a float but print as a binary for an int?

You have the source, so you always have a look at it, and see exactly why.