Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino sprintf float not formatting

I have this arduino sketch,

char temperature[10]; float temp = 10.55; sprintf(temperature,"%f F", temp); Serial.println(temperature); 

temperature prints out as

? F 

Any thoughts on how to format this float? I need it to be a char string.

like image 641
Mistergreen Avatar asked Dec 25 '14 21:12

Mistergreen


People also ask

What is Snprintf in Arduino?

The snprintf() function is defined in the <stdio. h> header file and is used to store the specified string till a specified length in the specified format. Characteristics of snprintf() method: The snprintf() function formats and stores a series of characters and values in the array buffer.

How do you limit a float to two decimal places in Arduino?

On arduino float is the same as a double. Your float will be of 6-7 decimal places of precision. If you want only two, you could multiply your float by 100 and cast it into an int or a long integer type.

What library is Sprintf in?

The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str.


1 Answers

Due to some performance reasons %f is not included in the Arduino's implementation of sprintf(). A better option would be to use dtostrf() - you convert the floating point value to a C-style string, Method signature looks like:

char *dtostrf(double val, signed char width, unsigned char prec, char *s) 

Use this method to convert it to a C-Style string and then use sprintf, eg:

char str_temp[6];  /* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/ dtostrf(temp, 4, 2, str_temp); sprintf(temperature,"%s F", str_temp); 

You can change the minimum width and precision to match the float you are converting.

like image 81
Dinal24 Avatar answered Sep 28 '22 20:09

Dinal24