Go Down

Topic: Method to print fixed-point values. (Read 937 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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy