float to string issue

Status
Not open for further replies.

Joe31093

Member
Just curious if anyone has come across this issue. I can't seem to convert a float to a string. My test code is below. I am running with PlatformIO with the latest updates. If I run the same code in Arduino IDE, it works fine. Trying to understand why it is failing in PlatformIO.

Hardware = Teensy3.6

Code:
#include <arduino.h>

int main()
{
	// Rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200
	Serial.begin(9600);

	int value1 = -12345;
	int value2 = 9876;
	float pi = 3.141596;
	char buffer[32];
	int copied = 0;

	while (true)
	{
		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%d", value1);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%d", value2);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		memset(buffer, 0x00, sizeof(buffer));
		copied = snprintf(buffer, sizeof(buffer), "%.4f", pi);
		Serial.print("copied: ");
		Serial.println(copied);
		Serial.print("buffer: ");
		Serial.println(buffer);

		delay(5000);
	}

	return 0;
}

Output:
copied: 6
buffer: -12345
copied: 4
buffer: 9876
copied: 0
buffer:

I tried using a template ostringstream method as well. It it crashes on ss << Number when the number is a float.

Code:
template <typename T> std::string to_string(const T& Number)
{
	std::ostringstream ss;
	ss << Number;
	return ss.str();
}
 
Last edited:
You might want to ask on the Platform IO forums.

But if I were to take a guess, the default print library may not support floating point. I remember with some compilers there was an option enable or disable floating point. Maybe there is an option to enable it?
 
I needed to add this to my sketch to get printf to support floats on teensy:

asm(".global _printf_float");

Works in platformio for me.
 
Thanks blackketter. That seems to have resolved the issue with snprintf.

Anyone have any idea on why the stringstream << float is failing?
 
Status
Not open for further replies.
Back
Top