1

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.

2 Answers 2

7

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!

Sign up to request clarification or add additional context in comments.

3 Comments

To anyone reading: I wouldn't recommend this approach, unless it's some very basic sketch. The reason is that 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.
@the.Legend - but 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.
You can import #include <string>
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.