This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

sprintf for floats. SES "PrintF Floating Point Supported" does not work

I am trying to use sprintf to format a float type variable, and I am not having any luck. The values printed are either blank or wrong. Sometimes I even Hardfault, which I believe is a buffer overflow from sprintf trying to print too many characters.

Before you ask, yes I changed "PrintF Floating Point Supported" as shown in the following answer:

https://devzone.nordicsemi.com/f/nordic-q-a/30535/nrf52-printf-float-in-ses

I have tried both "Float" and "Double", neither seems to do anything. 

I am using SEGGER Embedded Studio 5.42.

Code: (I had to use snprintf to avoid a buffer overflow)

char buf[20];

float f = 12.34;

printf("printf: %f\n", f);

snprintf(buf, 20, "%f", f);

printf("sprintf: %s\n", buf);

result:

printf: 80298907385281280000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
sprintf: 8029892515591747200

Previously it would print "0.000000" but it changes based on the value I try to print. 

I wrote my own version of ftoa to get around this problem for now but it is not an ideal workaround. 

float f = 12.34;
ftoa(f, buf, 10);
printf("ftoa: %s\n", buf);

result:

ftoa: 12.3400000000

Any advice would be great, Thank you. 

Related