Skip to content

round() macro in Arduino.h #76

Open
@Koepel

Description

@Koepel

The function round() in "math.h" is okay, it returns a floating point number as expected.
The macro round() in "Arduino.h" is a bug. It can not handle large floating point numbers and it returns a long integer.
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
It could be renamed to something else, for example ROUND_INT().

The sketch below shows the difference. With the normal round() function it returns four times "1.50", and with the round() macro in "Arduino.h" it returns: "1.00", "1.50", "1.50", "0.00".

// Arduino IDE 1.81 with Arduino Uno

// The "#undef round" removes the round() macro in Arduino.h
// Try with and without the #undef round
// #undef round

void setup() 
{
  float x;
  Serial.begin( 9600);

  x = 15.0;
  x = round( x) / 10;   // a integer division with the macro
  Serial.println( x);   // wrong value with the macro

  x = 15.0;
  x = round( x) / 10.0; // always calculated with floats
  Serial.println( x);   // always okay

  x = 15.0;
  x = round( x);
  x /= 10;              // always calculated with floats
  Serial.println( x);   // always okay

  x = 1.5E+20;
  x = round( x);        // the macro fails
  x /= 1E+20;           // make it printable with Serial.println
  Serial.println( x);   // wrong value with macro 
}

void loop()
{
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions