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

How to print float values using SEGGER RTT

Hi, My question is similar to this devzone.nordicsemi.com/.../ but I can't get it to work.

I am using SEGGER_RTT_WriteString and sprintf for debugging, but I am not able to print a float value such as 3.1415. I use the folowing code for printing intergers and it works fine:

uint8_t int_value;

int_value = 129;

char int_str[80];

sprintf(int_str, "Integer value is %d\n", int_value);

SEGGER_RTT_WriteString(0, int_str);

I am then trying to print a float value in the same way, but I have had no success so far. I have tried with "%f", "%0.2f"etc, but the printing result is just nothing or 0.

float float_value;

float_value = 3.1415;

char float_str[80];

sprintf(float_str, "Float value is %f\n", float_value);

SEGGER_RTT_WriteString(0, float_str);

Any suggestions are very much appreciated. Thanks!

Parents
  • If you numbers are in the range that fits in an int (32 bit signed) i.e less than a few billion, then you can just write some simple code to split the number at the decimal point, and print the digits to the left of the point as an integer, then print a "." then print the digits to the right of the point.

    e.g.

    #define PRECISION 10000
    int intPart = (int) floatNumber;
    int decimalPart = (floatNumber - intPart) * PRECISION;
    
    prinf("%d.%d",intPart,decimalPart);
    

    This would give you an answer to 4 decimal places

    If however your number is something like 1.2345 E-9 then its you will need to pull in a library to handle that sort of complex display

Reply
  • If you numbers are in the range that fits in an int (32 bit signed) i.e less than a few billion, then you can just write some simple code to split the number at the decimal point, and print the digits to the left of the point as an integer, then print a "." then print the digits to the right of the point.

    e.g.

    #define PRECISION 10000
    int intPart = (int) floatNumber;
    int decimalPart = (floatNumber - intPart) * PRECISION;
    
    prinf("%d.%d",intPart,decimalPart);
    

    This would give you an answer to 4 decimal places

    If however your number is something like 1.2345 E-9 then its you will need to pull in a library to handle that sort of complex display

Children
No Data
Related