Go Down

Topic: Method to print fixed-point values. (Read 912 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()
{
}




Nick Gammon on multitasking Arduinos:
1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Go Up