简体   繁体   中英

How to convert a floating point number into a string with precision? Arduino C++

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM