Character Array to Float

Submitted by Jenn Case on Mon, 02/18/2013 - 08:48


Sometimes it is necessary to turn character arrays into floats. However, precision can be an issue when using some of the current functions. The following function turns character arrays into a float that is split from the front half and the back half. This is one method for a more precise float.


The following code shows the CharToFloat function that turns the split Character Array into a float. It should be noted that the function splits the float into a forward half and a back half. This is due to the Arduino's capabilities. Floats can only ever have 7 digits, which means if you need anymore than that, the accuracy of the float decreases. It will remember 7 of the numbers and then make the best guess it can for the rest. This can be a problem if precision is key.

And, no, using double will not fix the problem. In the Arduino, float and double are the same thing. Therefore, splitting the float into two sections can retain the accuracy with some inconvenience.

void CharToFloat(char* chars, double* value, int count) {
  int i=0, l=0;
  float multiplier;
  float front =0.0, behind =0.0;
  value = 0.0;
  //before demical point
  while(chars[i]!='.' && i<count) {
    if (chars[i]=='.') {
      int q=i;
for(int j=i; j>0; j--) { multiplier=1;
for(int k=q; k>1; k--) { multiplier *= 10; }
front+=(chars[l]-'0')*multiplier; l++; q--; }
l++; } } int n=i;
//after demical point while(chars[n]!='\0' && i<count) { n++; if (chars[n]=='\0') { int q=n, l=n-1;
for(int j=n-1; j>i; j--) { multiplier=1;
for(int k=q-(i+2); k>=0; k--) { multiplier = 0.1*multiplier; } behind+=(chars[l]-'0')*multiplier; l--; q--; } } }
value[0]=front; value[1]=behind; }

This may not be the most elegant way to turn a character array into a float, but it works. Needless to say, this does not appear to be common practice, but seems like it might be a common problem.