Happy little incident #9

Mcu32

Well-known member
A pretty minor bug, but still a bug and very easy to fix, zero costs:

Code:
void incident_9()
{
  char buffer[20];
  float normalNumber = 12.34;
  float nanNumber = NAN; // Generates a "Not a Number"
  Serial.println("--- width = 10 (Should be right-aligned: spaces IN FRONT) ---");
  // 1. Normal number (Works correctly)
  dtostrf(normalNumber, 10, 2, buffer);
  Serial.print("Normal: '");
  Serial.print(buffer);
  Serial.println("'");
  // Output: '     12.34' (Correctly right-aligned)
  // 2. NaN with the bug (Behaves incorrectly)
  dtostrf(nanNumber, 10, 2, buffer);
  Serial.print("NaN   : '");
  Serial.print(buffer);
  Serial.println("'");
  // Incorrect output in the old code: 'NAN       ' (Wrong, it's left-aligned!)

  Serial.println("\n\n--- width = -10 (Should be left-aligned: spaces BEHIND) ---");
  // 3. Normal number (Works correctly)
  dtostrf(normalNumber, -10, 2, buffer);
  Serial.print("Normal: '");
  Serial.print(buffer);
  Serial.println("'");
  // Output: '12.34     ' (Correctly left-aligned)
  // 4. NaN with the bug (Behaves incorrectly)
  dtostrf(nanNumber, -10, 2, buffer);
  Serial.print("NaN   : '");
  Serial.print(buffer);
  Serial.println("'");
  // Incorrect output in the old code: '       NAN' (Wrong, it's right-aligned!)
}

Fix: The initial if (width < 0) in the NaN and Inf blocks must be changed to if (width > 0).
 
Back
Top