Arduino Convert Float To Char Array

Posted on

Arduino dtostrf() Function

To convert a floating-point number to a character array in Arduino Programming, we need dtostrf() function In this article, I will share how to use this function Arduino Convert Float To Char Array.

If you are still confused about the difference between a char array and a string, you can read about it in the Arduino Char Array vs String Explanation article.

The dtostrf() function is not part of the standard C library, so it is specific to Arduino. It takes four arguments:

  1. The floating-point number to be converted
  2. The width of the field in which the number will be printed
  3. The precision of the number, or the number of digits after the decimal point
  4. The character array in which the converted number will be stored

How to use it

Here’s an example of how you might use dtostrf():

float pi = 3.14159265;
char result[10];
dtostrf(pi, 5, 2, result);

This will convert the value of pi to a character array, with a width of 5 characters and a precision of 2, and store the result in the result array. The resulting character array will contain the string “3.14”.

Note:

  1. The dtostrf() function is inefficient, and it can take up a lot of memory if you convert a large number of floating-point numbers. If you need to convert many numbers, you may consider using a different method.
  2. The dtostrf() function does not support scientific notation. If you need to convert a number in scientific notation, you will need to use a different method.

Hopefully, this Arduino Convert Float To Char Array article can be helpful.

Read more: