Pages: [1]   Go Down
Author Topic: Method to print fixed-point values.  (Read 861 times)
0 Members and 1 Guest are viewing this topic.
Pittsburgh, PA, USA
Offline Offline
Faraday Member
**
Karma: 98
Posts: 4803
I learn a bit every time I visit the forum.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:

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()
{
}



Logged

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

Pages: [1]   Go Up
Jump to: