How to convert text into a float number in C

110 Views Asked by At

I am writing a code that would parse incoming UART messages and extract the information that I want. I will be sending a command and then a floating number for example:

"SET_VOLTAGE:2.4"

I would like to know how can I parse the "2.4" in to an actual float number 2.4 I have tried to use atof function but it didint work. Probably because I have "."in the middle.

I have a temp_buffer that holds "2.4"and I need to convert it to float number.

My temp_buffer contains the following bytes:

temp_buf[0]=50

temp_buf[1]=46

temp_buf[2]=53

temp_buf[3]=0

My test code:

  float number;
  float number2;
  char test_buf[4] = {50,46,53,0};
  for(int i = 0; i < 4 ; i++){
      printf("test_buf[%i] = %u \n",i,test_buf[i]);
  }
  number = atof(test_buf);
  number2 = strtod(test_buf,NULL);
  printf("FLOAT NUMBER = %.2f \n",number);
  printf("FLOAT NUMBER2 = %.2f \n",number2);

printf output:

test_buf[0] = 50 
test_buf[1] = 46 
test_buf[2] = 53 
test_buf[3] = 0 
FLOAT NUMBER = 0.00 
FLOAT NUMBER2 = 0.00 

UPDATE trying strtod: I have tried to use a function that has been suggested for me:

    static double get_double(const char *str)
    {
        /* First skip non-digit characters */
        /* Special case to handle negative numbers */
        while (*str && !(isdigit(*str) || ((*str == '-' || *str == '+') && isdigit(*(str + 1)))))
            str++;

        /* The parse to a double */
        return strtod(str, NULL);
    }

In my main.c I have:

  double number;
  double number2;
  char test_buf[4] = {50,46,53,0};
  char test_buf2[4] = {'2','.','5','\0'};
  number = get_double(test_buf);
  number2 = get_double(test_buf2);
  printf("number = %d \n",number);
  printf("number2 = %d \n",number2);

That still does not seem to work, the serial monitor output:

number = 0 
number2 = 0 

UPDATE2 Trying strtof

  char test_buf2[4] = {'2','.','5','\0'};
  char test_buf3[] = "2.5";

  float float1 = strtof(test_buf2, NULL);
  printf("float1 = %.2f \n",float1);

  float float2 = strtof(test_buf3, NULL);
  printf("float2 = %.2f \n",float2);

The results:

float1 = 1075838976.00 
float2 = 1075838976.00 

UPDATE3 Include #include <stdlib.h>

It turns out that in order for strtof to wurk I must include "stdlib.h"even though I didint get any warnings. Now strtof seems to work fine but strtod still does not work.

0

There are 0 best solutions below