Arduino sprintf float not formatting

前端 未结 4 856
离开以前
离开以前 2020-12-02 16:50

I have this arduino sketch,

char temperature[10];
float temp = 10.55;
sprintf(temperature,\"%f F\", temp);
Serial.println(temperature);

tem

4条回答
  •  旧时难觅i
    2020-12-02 17:32

    Due to some performance reasons %f is not included in the Arduino's implementation of sprintf(). A better option would be to use dtostrf() - you convert the floating point value to a C-style string, Method signature looks like:

    char *dtostrf(double val, signed char width, unsigned char prec, char *s)
    

    Use this method to convert it to a C-Style string and then use sprintf, eg:

    char str_temp[6];
    
    /* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
    dtostrf(temp, 4, 2, str_temp);
    sprintf(temperature,"%s F", str_temp);
    

    You can change the minimum width and precision to match the float you are converting.

提交回复
热议问题