string 在arduino草图中将double类型转换为字符串类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19867227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:09:43  来源:igfitidea点击:

convert double type into string type in arduino sketch

stringarduinodouble

提问by Yang

double ambientTemp=44.00;
String yourdatacolumn="yourdata=";
String yourdata; 
double yourarduinodata=ambientTemp; 
yourdata = yourdatacolumn + yourarduinodata; 

//I want the output to be string. but because of yourarduinodata is double type. Can not convert it to string. then , I put (String) in front of yourarduinodata, still doesn't let me run throught.

//我希望输出是字符串。但因为 yourarduinodata 是双类型。无法将其转换为字符串。然后,我把 (String) 放在 yourarduinodata 前面,仍然不让我跑通。

Anyone has any idea about convert double type into string type in arduino sketch;

任何人都知道在 arduino 草图中将 double 类型转换为 string 类型;

回答by Dani Bresler

Another Way To Convert Double To String:

将 Double 转换为字符串的另一种方法:

    char TempString[10];  //  Hold The Convert Data

    dtostrf(ambientTemp,2,2,TempString);
 // dtostrf( [doubleVar] , [sizeBeforePoint] , [sizeAfterPoint] , [WhereToStoreIt] )
    YourArduinoData = String(TempString);  // cast it to string from char 

回答by Abhishek Pachlegaonkar

Use - String(val, decimalPlaces)

用 - String(val, decimalPlaces)

example,

例子,

double a = 10.2010;

String SerialData="";

SerialData = String(a,4);

Serial.println(SerialData);

回答by Octopus

Something like this might work:

像这样的事情可能会奏效:

String double2string(double n, int ndec) {
    String r = "";

    int v = n;
    r += v;     // whole number part
    r += '.';   // decimal point
    int i;
    for (i=0;i<ndec;i++) {
        // iterate through each decimal digit for 0..ndec 
        n -= v;
        n *= 10; 
        v = n;
        r += v;
    }

    return r;
}