To convert a number to a string on Arduino, use the built-in String() function for integers and floats, or the C-style dtostrf() function for precise float formatting. The simplest one-liner is String myString = String(1234); which gives you "1234", and for a float with two decimals you can write String myString = String(3.14159, 2); to get "3.14".
Why You Need Number-to-String Conversion
Arduino boards communicate with displays, SD cards, and serial monitors through text. When you send data over Serial.print(), the library handles the conversion internally, but many functions require a char[] or String object first. For example, an OLED display library like Adafruit_SSD1306 expects setCursor() followed by print(), which works with numbers directly, but if you want to concatenate a number with a unit like " cm", you must convert the number to a string. Similarly, writing to an SD card with file.println() accepts strings only. Understanding both conversion methods lets you choose the right tool for memory-constrained microcontrollers.
The String() Function: Simple and Readable
The String() constructor is part of the Arduino core and converts any primitive type to a String object. Its syntax is String(value) or String(value, baseOrDecimals). For integers, the second parameter is the base (default 10, use 2 for binary, 16 for hex). For floats, the second parameter is the number of decimal places (default 2). Examples:
String(42)returns"42"String(255, HEX)returns"ff"(lowercase)String(3.14159, 4)returns"3.1416"(rounds)String(analogRead(A0))converts an integer reading
This method is beginner-friendly and handles negative numbers automatically. However, it allocates memory on the heap dynamically, which can fragment the limited RAM of an Arduino Uno (2 KB). For a few conversions per second, this is fine, but in a loop that creates thousands of strings, you risk memory leaks unless you call myString.reserve() or avoid repeated creation.
The dtostrf() Function: Precise Float Control
For embedded systems, dtostrf() is the preferred method because it writes into a pre-allocated char buffer, avoiding dynamic memory. The syntax is dtostrf(floatValue, minWidth, numDecimals, charBuffer). It returns a pointer to the buffer. Example:
char buffer[10];
dtostrf(3.14159, 1, 2, buffer); // buffer becomes "3.14"
The minWidth parameter pads with spaces if the number is shorter; use 1 to avoid padding. The numDecimals controls rounding. This function is declared in <stdlib.h>, which is included by default in Arduino. It does not handle negative numbers with a leading minus sign correctly if the width is too small, so always allocate enough space (e.g., for a float like -123.45, use at least 8 characters).
Comparing String vs char[] for Memory and Speed
Arduino boards have limited RAM. A String object uses about 12 bytes of overhead plus the character data, and it dynamically allocates memory on the heap. A char[] array uses exactly the bytes you declare. For long-running programs, repeated String creation can cause heap fragmentation, where free memory becomes scattered and eventually the board runs out of RAM. The dtostrf() approach uses a fixed buffer, so memory usage is predictable. Speed-wise, dtostrf() is faster because it does not allocate memory. For a simple integer conversion, String() is fine, but for floats in a loop, use dtostrf(). If you must use String, call myString = ""; to clear it and reuse the same object.
Common Pitfalls and How to Avoid Them
One frequent mistake is using String concatenation with numbers directly, like String msg = "Value: " + 123; which does not compile because the compiler tries to add a pointer to an integer. Instead, write String msg = "Value: " + String(123);. Another pitfall is passing a String to a function that expects a char*; use myString.c_str() to get a C-string pointer. Also, when using dtostrf(), remember that the buffer must be large enough to hold the minus sign, digits, decimal point, and null terminator. For a float with 2 decimals and a max value of 999, use char buf[7] (3 digits + dot + 2 decimals + null). If the buffer is too small, the function will overflow and corrupt memory.
Practical Example: Displaying Sensor Data
Suppose you read a temperature sensor that returns a float like 23.4567 and you want to show it on a 16×2 LCD. With String():
float temp = 23.4567;
String out = String(temp, 1); // "23.5"
lcd.print(out);
With dtostrf():
char out[6];
dtostrf(temp, 1, 1, out); // "23.5"
lcd.print(out);
Both work, but the second avoids heap allocation. For serial output, you can skip conversion entirely: Serial.println(temp, 1); prints with one decimal. But if you need to send a formatted string over a radio module that expects a char[], dtostrf() is the way.
Alternatives: sprintf() and Manual Conversion
The C library function sprintf() can format numbers into a buffer, but on Arduino it does not support floating point by default because the %f format specifier is not implemented in the standard library to save space. You can use %d for integers and %x for hex, but for floats you must use dtostrf() first. Example:
char msg[32];
int val = 42;
sprintf(msg, "Value: %d", val); // "Value: 42"
For floats, combine them:
char tmp[10];
dtostrf(3.14, 1, 2, tmp);
char msg[32];
sprintf(msg, "Pi = %s", tmp);
Manual conversion (extracting digits with division and modulo) is possible but tedious and error-prone for negative numbers and floats. Avoid it unless you are on an extremely memory-constrained board like an ATtiny.
Frequently Asked Questions
How do I convert an int to a char array in Arduino? Use itoa() from <stdlib.h>: char buf[6]; itoa(12345, buf, 10); gives "12345". For floats, use dtostrf() instead.
Why does String(1.0) return “1.00”? Because the default decimal places for a float in String() is 2. To get just “1”, use String(1.0, 0) or convert to an integer first.
Can I convert a string back to a number? Yes, use toInt() for integers and toFloat() for floats on a String object. For char[], use atoi() and atof().
Does dtostrf round or truncate? It rounds to the nearest value. For example, dtostrf(2.345, 1, 2, buf) gives “2.35” because the third decimal is 5, which rounds up.
Is String() safe to use in an interrupt routine? No. Dynamic memory allocation is not interrupt-safe. Use dtostrf() with a pre-allocated buffer inside an ISR.
What is the maximum length of a string I can create? Limited by free RAM. On an Uno, you have about 2 KB, so a 1000-character string is possible but leaves little room for other variables. Always reserve space with myString.reserve(len) to avoid reallocation.
Related
- How to Set Enum Value in Java (with Code Examples)
- How to Save Maya File as FBX
- Balloon Payment Calculator: Fixed Payment Basics
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Train-Test Split: Purpose, Methods, and Common MistakesA train-test split function divides a dataset into separate portions: one for fitting a machine-learning model and another…
- How to Embed a Video With Sound in PowerPoint SlidesTo embed a video with sound in PowerPoint, choose Insert > Video > This Device on Windows, select…
- Delivery Schedule Excel: Create and Manage a Delivery PlanA delivery schedule in Excel is a workbook that records each shipment, its planned delivery date, its actual…
- How to Eliminate Duplicates in Google Sheets QuicklyTo eliminate duplicates in Google Sheets, select the data range, then choose Data > Data cleanup > Remove…
- Google Sheets COUNTIF Range: Syntax, Examples, and FixesIn Google Sheets, COUNTIF counts cells in a range that meet one condition. The basic formula is =COUNTIF(A2:A20,"Open");…
- How to Freeze Rows and Columns in ExcelTo freeze rows or columns in Excel for Microsoft 365 on Windows, select the cell just below the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.