Go Down

Topic: Method to print fixed-point values. (Read 903 times) previous topic - next topic

GoForSmoke

This is a tested demo of printFixedDec(long value, long scale).

Code: [Select]


void setup()
{
  long val = 12345678L;
  long scale = 1000L; // 3-decimal places scale

  Serial.begin(9600);
  Serial.print( "DEMO: start val = " ); 
  Serial.print( val, DEC );
  Serial.print( " mm == " );
  //  Serial.print( val / scale );
  //  Serial.print( "." );
  //  Serial.print( val % scale );
  printFixedDec( val, scale );
  Serial.print( " m == " );
  printFixedDec( val, ( scale = 1000000 ));
  Serial.println( " Km" );
  Serial.println( );
  Serial.print( "22 / 7 = " );
  scale = 10000000;
  printFixedDec( 22 * scale / 7, scale );
  Serial.println( );
}

void printFixedDec( long val, long scale )  // we don't need no steenking loops!
{
  Serial.print( val / scale );  // printing the left-side digits
  Serial.print( "." );               // then the dec pt
  Serial.print( val % scale );  // then the remainder to scale
}

void loop()
{
}




I find it harder to express logic in English than in Code.
Sometimes an example says more than many times as many words.

Go Up