Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with

    char charVal[5];               //temporarily holds data from vals 
    String stringVal = "";     //data on buff is copied to this string

    dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
    //convert chararray to string
    for(int i=0;i<sizeof(charVal);i++)
    {
    stringVal+=charVal[i];
    }
    GPS_string = GPS_string + "Car location: \nlat:" + stringVal; 
    stringVal = "";

and it given me an error :

error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,
share|improve this question
up vote 0 down vote accepted

This has been answered in the previous question but I can repeat it here:

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

An alternative is to use dtostrf() as in your snippet:

void loop()
{
  ...    
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

Cheers!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.