简体   繁体   English

如何将浮点数转换为精确的字符串? Arduino C++

[英]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我有一个像3.14159这样的数字,我希望它是3.1

Arduino is being fussy with libraries for some reason. Arduino 出于某种原因对库很挑剔。 At the moment I can't use the string library.目前我无法使用string库。

I ended up finding an awesome solution to this.我最终找到了一个很棒的解决方案。 Turns out Arduino has a method for this!原来 Arduino 有一个方法! It's just the String() method.这只是String()方法。 So in order to convert 3.14159 simply type ⤵︎所以为了转换3.14159只需输入 ⤵︎

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.由于默认情况下sprintf不支持标准 Arduino 环境中的浮点数,因此 avr-gcc 附带了 dtostrf() ,它可以满足您的需求。 Sample usage here示例用法在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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