Pages: [1]   Go Down
Author Topic: String to Float conversion issue  (Read 929 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am attempting to read a value from a file on an SD card, which ultimately need to end up as a float, so i can do some math with it.  I am not having any issues getting the value from the sd card as a string (or really an array of chars), but when i attempt attempt to convert that to a float i am losing the 3rd decimal place on.  The file on the SD card has: 37.639693 in it

Here's my code:

Code:
#include <SD.h>
const int chipSelect = 10;

File targetFile;
float targetLat ;
char FileData[10];

void setup()
{
  Serial.begin(9600);
   pinMode(10, OUTPUT);
   
      // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    }
   
    targetFile = SD.open("target.txt");
   
    byte index = 0;
   
    //if the file is open...
    if (targetFile){
      //keep reading chars till there are no more
    while (targetFile.available()){
      FileData[index] = targetFile.read();
      index++;
      }
      //Filedata has a char array representation of a float.
    targetLat = atof(FileData);
    }
}

void loop(){
  Serial.print("Chars:");
  Serial.println(FileData);
  Serial.print("Float:");
  Serial.println(targetLat);

 delay (20000);
}



And here is the output from the code:

Chars:37.639693
Float:37.64

I have also tried using "strtod" with the same results.  Any idea how i can get my float  value with precision I am looking for?

Thanks,

Steve
Logged

Gosport, UK
Offline Offline
Faraday Member
**
Karma: 21
Posts: 3113
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

http://arduino.cc/en/Serial/Print

Quote
Floats are similarly printed as ASCII digits, defaulting to two decimal places.

Quote
An optional second parameter specifies the base (format) to use; permitted values are BIN (binary, or base 2), OCT (octal, or base 8 ), DEC (decimal, or base 10), HEX (hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks!  I was looking at it from a data problem not a display problem.  I knew it was something simple that I was overlooking! smiley-lol

Thanks again,
Steve
Logged

Pages: [1]   Go Up
Jump to: