Pages: [1] 2 3   Go Down
 Author Topic: printing a double variable  (Read 35650 times) 0 Members and 1 Guest are viewing this topic.
0
Offline
God Member
Karma: 2
Posts: 854
Arduino rocks!
 « on: April 03, 2008, 07:42:28 am » Bigger Smaller Reset

How can I print a double precision variable to the serial port?

With something like

double x;
double y;
double z;

x = 10;
y = 3.1;
z = x / y;

serial.println (z);

It displays "3".

Also, I used millis to time the "z = x / y;" line and it seems to take about 1/10th of a millisecond.  Is it really doing 64 bit floating point division in a fraction of a millisecond?  I was expecting something in the 10ms or more range.
 Logged

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #1 on: April 03, 2008, 08:27:57 am » Bigger Smaller Reset

Serial.print does not print floating point. Here is a sketch with a function you can use to display the number of decimal places you want.

Code:
double x;
double y;
double z;

void printDouble( double val, unsigned int precision){
// prints val with number of decimal places determine by precision
// NOTE: precision is 1 followed by the number of zeros for the desired number of decimial places
// example: printDouble( 3.1415, 100); // prints 3.14 (two decimal places)

Serial.print (int(val));  //prints the int part
Serial.print("."); // print the decimal point
unsigned int frac;
if(val >= 0)
frac = (val - int(val)) * precision;
else
frac = (int(val)- val ) * precision;
Serial.println(frac,DEC) ;
}

void  setup(){
Serial.begin(9600);
Serial.println("Print floating point example");
printDouble( 3.1415, 100);  // example of call to printDouble to print pi to two decimal places
x = 10;
y = 3.1;
z = x / y;
}

void loop(){
printDouble(z,10);   // one decimal place
printDouble(z,100);  // two decimal places
printDouble(z,1000); // three decimal places
z = z + .1;
delay(100);
}
 « Last Edit: April 03, 2008, 08:41:06 am by mem » Logged

0
Offline
God Member
Karma: 2
Posts: 854
Arduino rocks!
 « Reply #2 on: April 03, 2008, 10:55:16 am » Bigger Smaller Reset

Thanks.  I'll try it out when I get home.
 Logged

0
Offline
Newbie
Karma: 0
Posts: 13
Arduino rocks
 « Reply #3 on: July 16, 2008, 03:29:34 am » Bigger Smaller Reset

printDouble( 1.06, 100 );     ----------------> prints 1.5

Any idea how one would zero pad that to get the correct value? even if it came out 1.05, that'd be ok.
Thanks
 Logged

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #4 on: July 16, 2008, 07:02:22 am » Bigger Smaller Reset

Try the modified code here, I have not had a chance to test it so please let me if it works or not.

Code:
void printDouble( double val, unsigned int precision){
// prints val with number of decimal places determine by precision
// NOTE: precision is 1 followed by the number of zeros for the desired number of decimial places
// example: printDouble( 3.1415, 100); // prints 3.14 (two decimal places)

Serial.print (int(val));  //prints the int part
Serial.print("."); // print the decimal point
unsigned int frac;
if(val >= 0)
frac = (val - int(val)) * precision;
else
frac = (int(val)- val ) * precision;
int frac1 = frac;
while( frac1 /= 10 )
precision /= 10;
precision /= 10;
while(  precision /= 10)
Serial.print("0");

Serial.println(frac,DEC) ;
}

When I get a chance, I will change the function so the second argument is the actual number of decimal places (not 1 with the number of zeros indicating decimal places) to make the fix simpler. But I hope this will get you going
 « Last Edit: July 16, 2008, 07:02:57 am by mem » Logged

0
Offline
Newbie
Karma: 0
Posts: 13
Arduino rocks
 « Reply #5 on: July 16, 2008, 11:40:59 am » Bigger Smaller Reset

works great!
thanks again
 Logged

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #6 on: July 16, 2008, 12:57:44 pm » Bigger Smaller Reset

Good to hear it works. Here is an improved version, it takes the number of decimal places as the second argument. It also handles the full precision of a double on the Arduino ( up to 6 decimal places).

A cr/lf is no longer sent, so that multiple prints can be done on one line, free to add a Serial.println() at the end if you want.

Code:
void printDouble( double val, byte precision){
// prints val with number of decimal places determine by precision
// precision is a number from 0 to 6 indicating the desired decimial places
// example: printDouble( 3.1415, 2); // prints 3.14 (two decimal places)

Serial.print (int(val));  //prints the int part
if( precision > 0) {
Serial.print("."); // print the decimal point
unsigned long frac;
unsigned long mult = 1;
while(precision--)
mult *=10;

if(val >= 0)
frac = (val - int(val)) * mult;
else
frac = (int(val)- val ) * mult;
unsigned long frac1 = frac;
while( frac1 /= 10 )
Serial.print("0");
Serial.print(frac,DEC) ;
}
}

Unfortunatly, no opportunity to test this myself tonight so any feedback is welcome.

 Logged

0
Offline
Newbie
Karma: 0
Posts: 13
Arduino rocks
 « Reply #7 on: July 16, 2008, 02:08:41 pm » Bigger Smaller Reset

also works great!
thank you thank you
 Logged

0
Offline
Newbie
Karma: 0
Posts: 5
Arduino rocks
 « Reply #8 on: September 05, 2008, 01:25:14 am » Bigger Smaller Reset

thanks for sharing
 Logged

0
Offline
Jr. Member
Karma: 0
Posts: 94
Arduino rocks
 « Reply #9 on: October 09, 2008, 12:13:51 am » Bigger Smaller Reset

mem,

How might you rewrite the "printDouble" function to return a string instead of printing to the serial port?

I need to create a string of comma separated data, and some of the data contains floats that i want to format. i want to create the whole string then check the length before i send it to the serial port.

i was thinking of using sprintf for this but then found out that it doesn't support floats.
so i was thinking, instead of passing in a float to sprintf i would pass in a string of a float that was already formatted by a new version your "printDouble" function.

Thanks
Jeff
 Logged

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #10 on: October 09, 2008, 03:35:28 am » Bigger Smaller Reset

Hi jeff,

printDouble uses the print formatting routines in the Serial library to do the conversion from number to characters, so I don't think there is an easy way to do what you want without messing with the low level formatting routines used by print.

One idea that comes to mind is to do a very simple version of printf for output to the serial port that handles arguments for strings, integers and floats but does not have all the fancy flags in a full printf implementation. Even a much simplified printf isn't easy, but I will see if I can come up with a quick way of putting something together. Don't count on it though
 Logged

Portland, OR, USA
Offline
Jr. Member
Karma: 0
Posts: 78
 « Reply #11 on: October 28, 2008, 03:57:52 pm » Bigger Smaller Reset

Quote
How might you rewrite the "printDouble" function to return a string instead of printing to the serial port?
Here is some code (derived from that posted by mem) to produce a string in a buffer corresponding to a floating point value.  The helper function fmtUnsigned() will produce a string in a buffer corresponding to an unsigned integral value with optional leading zero padding.
Code:
void fmtDouble(double val, byte precision, char *buf, unsigned bufLen = 0xffff);
unsigned fmtUnsigned(unsigned long val, char *buf, unsigned bufLen = 0xffff, byte width = 0);

//
// Produce a formatted string in a buffer corresponding to the value provided.
// If the 'width' parameter is non-zero, the value will be padded with leading
// zeroes to achieve the specified width.  The number of characters added to
// the buffer (not including the null termination) is returned.
//
unsigned
fmtUnsigned(unsigned long val, char *buf, unsigned bufLen, byte width)
{
if (!buf || !bufLen)
return(0);

// produce the digit string (backwards in the digit buffer)
char dbuf[10];
unsigned idx = 0;
while (idx < sizeof(dbuf))
{
dbuf[idx++] = (val % 10) + '0';
if ((val /= 10) == 0)
break;
}

// copy the optional leading zeroes and digits to the target buffer
unsigned len = 0;
byte padding = (width > idx) ? width - idx : 0;
char c = '0';
while ((--bufLen > 0) && (idx || padding))
{
else
c = dbuf[--idx];
*buf++ = c;
len++;
}

*buf = '\0';
return(len);
}

//
// Format a floating point value with number of decimal places.
// The 'precision' parameter is a number from 0 to 6 indicating the desired decimal places.
// The 'buf' parameter points to a buffer to receive the formatted string.  This must be
// sufficiently large to contain the resulting string.  The buffer's length may be
// optionally specified.  If it is given, the maximum length of the generated string
// will be one less than the specified value.
//
// example: fmtDouble(3.1415, 2, buf); // produces 3.14 (two decimal places)
//
void
fmtDouble(double val, byte precision, char *buf, unsigned bufLen)
{
if (!buf || !bufLen)
return;

// limit the precision to the maximum allowed value
const byte maxPrecision = 6;
if (precision > maxPrecision)
precision = maxPrecision;

if (--bufLen > 0)
{
// check for a negative value
if (val < 0.0)
{
val = -val;
*buf = '-';
bufLen--;
}

// compute the rounding factor and fractional multiplier
double roundingFactor = 0.5;
unsigned long mult = 1;
for (byte i = 0; i < precision; i++)
{
roundingFactor /= 10.0;
mult *= 10;
}

if (bufLen > 0)
{
// apply the rounding factor
val += roundingFactor;

// add the integral portion to the buffer
unsigned len = fmtUnsigned((unsigned long)val, buf, bufLen);
buf += len;
bufLen -= len;
}

// handle the fractional portion
if ((precision > 0) && (bufLen > 0))
{
*buf++ = '.';
if (--bufLen > 0)
buf += fmtUnsigned((unsigned long)((val - (unsigned long)val) * mult), buf, bufLen, precision);
}
}

// null-terminate the string
*buf = '\0';
}
 « Last Edit: October 28, 2008, 04:00:50 pm by dkinzer » Logged

Don

ZBasic Microcontrollers
http://www.zbasic.net

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #12 on: October 28, 2008, 04:32:45 pm » Bigger Smaller Reset

Hi Don, nicely done !
 « Last Edit: October 28, 2008, 04:34:24 pm by mem » Logged

London
Offline
Tesla Member
Karma: 10
Posts: 6250
Have fun!
 « Reply #13 on: November 16, 2008, 10:08:28 pm » Bigger Smaller Reset

Latest code for serial port and version 0012 text lcd library. This code has a fix to correctly print the sign of small negative numbers

Serial version:
Code:
void printDouble( double val, byte precision){
// prints val with number of decimal places determine by precision
// precision is a number from 0 to 6 indicating the desired decimial places
// example: lcdPrintDouble( 3.1415, 2); // prints 3.14 (two decimal places)

if(val < 0.0){
Serial.print('-');
val = -val;
}

Serial.print (int(val));  //prints the int part
if( precision > 0) {
Serial.print("."); // print the decimal point
unsigned long frac;
unsigned long mult = 1;
while(precision--)
mult *=10;

if(val >= 0)
frac = (val - int(val)) * mult;
else
frac = (int(val)- val ) * mult;
unsigned long frac1 = frac;
while( frac1 /= 10 )
Serial.print("0");
Serial.print(frac,DEC) ;
}
}

version for the Arduino 0012 liquid crystal library (change print to printIn for the older lcd library)
Code:
void lcdPrintDouble( double val, byte precision){
// prints val on a ver 0012 text lcd with number of decimal places determine by precision
// precision is a number from 0 to 6 indicating the desired decimial places
// example: printDouble( 3.1415, 2); // prints 3.14 (two decimal places)

if(val < 0.0){
lcd.print('-');
val = -val;
}

lcd.print (int(val));  //prints the int part
if( precision > 0) {
lcd.print("."); // print the decimal point
unsigned long frac;
unsigned long mult = 1;
while(precision--)
mult *=10;

if(val >= 0)
frac = (val - int(val)) * mult;
else
frac = (int(val)- val ) * mult;
unsigned long frac1 = frac;
while( frac1 /= 10 )
lcd.print("0");
lcd.print(frac,DEC) ;
}
}
 Logged

Concón, Chile, South América
Offline
Full Member
Karma: 0
Posts: 150
Try to interface my car with Arduino
 « Reply #14 on: November 17, 2008, 02:42:50 pm » Bigger Smaller Reset

Dear Mem,

The routine for printing decimals in an LCD display you posted, didn´t work for me.

The double definition of variables doesn´t show in my manual, only :

Int
byte
long
float
array

Besides, I have never progam in C before, only in BASIC.
So, I don´t know where should I put your routine: all instructions together, a part at the beginning, etc.

Consider I am using a display called GDM1602K Xiamen Ocular, using LCD4bit driver.

Hope you can help me a little more....

Any ideas?
 Logged

 Pages: [1] 2 3   Go Up