I have a number like 3.14159 and I want it to be 3.1
Arduino is being fussy with libraries for some reason. At the moment I can't use the string library.
I ended up finding an awesome solution to this. Turns out Arduino has a method for this! It's just the String() method. So in order to convert 3.14159 simply type ⤵︎
float num = 3.14159
String str1 = String(num, 1) // 3.1
String str2 = String(num, 2) // 3.14
String str3 = String(num, 3) // 3.141
So on the right of the comma is the decimal places parameter. It has a lot of functionality but that's one of the overloads. You can see them all here!
String is not equivalent to std::string and would fragment memory in the long run. A String is an object supported by the String library. Using them is likely to fragment memory usage which with the limited resources available on the Arduino can cause problems. A std::string is an array of chars terminated by a null. Using them does not fragment memory because they are not continually created and destroyed.std::string isn't available in Arduino as the STL isn't supported there. Since Arduino is referenced in the title and the solution, not sure it's relevant here.#include <string>As by default sprintf does not support floats in a standard Arduino environment, there's dtostrf() coming with avr-gcc, which does what you want. Sample usage here