Introduction: Converting Float to String and Character Array in a Few Simple Steps - Arduino

Picture of Converting Float to String and Character Array in a Few Simple Steps - Arduino

Do you want to convert an floating point value to a string? If that is so, then there are two methods that i found really helpful.

Step 1: Float to String Using Dtostrf

dtostrf is a function that converts a float or double into a character array using only one line of code

dtostrf(float, minimum width, precision, character array);

You also need to include the stdlib.h library for this function to work. However, in my case it worked with or without including the library.

Here is the code to show you how to do that.

Step 2: Improvised Function

I realized that dtostrf does not work with all arduino based boards. For instance, when using the rfDuino i got an error:

Infinite_Delay_revision.ino: In function 'void RFduinoBLE_onReceive(char*, int)':
Infinite_Delay_revision:93: error: 'dtostrf' was not declared in this scope

So, i decided to create a function that extracts the decimal part of the floating point number and parses it on as an integer. Then I combined the string equivalent of the whole part and the string equivalent of the decimal part with a full stop at the center.

The code is attached below.

It works for both floats and doubles. For more information visit the link below.

Converting float to string

Comments

泳志葉 (author)2016-06-21

dtostrf.ino: In function 'void setup()':

dtostrf.ino:9:34: error: 'dtostrf' was not declared in this scope

tasercake (author)泳志葉2016-06-23

have you imported the required library?

You need to add the following line at the beginning of your code for this to work:

#include<stdlib.h>

wilgubeast (author)2014-09-24

Not everyone will find this useful. But those that do will find it VERY helpful. Thanks for sharing!

About This Instructable

49,986views

19favorites

License:

Bio: I am an electrical engineer and an Arduino and electronics enthusiasts. I believe working with electricity should be fun as well as beneficial to engineers ... More »
More by yhtomitsy:RFduino - Sending and Receiving Data Via BLE Arduino redback simple serverConfiguring xBee in API mode
Add instructable to: