简体   繁体   English

在 Arduino 中将浮点数转换为字符串

[英]Convert Float to String in Arduino

I have a few question, how do I convert Float to String?我有几个问题,如何将浮点数转换为字符串?

Because my OLED display require 'String' and cannot print Float因为我的 OLED 显示器需要“字符串”并且无法打印 Float

Here is my coding这是我的编码

  WindSpeed = WIND_SPEED_20_PULSE_SECOND / ONE_ROTATION_SENSOR * (float) Rotations;
  float SpeedMPH = ((WindSpeed * 3600) / CONVERTMPH_FORMULA);
  String WindSpeedMS = WindSpeed;
  if((millis() - Start_Read_Timer) >= READ_TIME)
  {
    cli();

    WindSpeedStatus();
    
    sei();

    Rotations = 0;
    Start_Read_Timer = millis();
  }
    display.setFont(ArialMT_Plain_24);
  display.drawString(0, 20, WindSpeedMS);
  display.display();
  delay(500);

The error I got is:我得到的错误是:

Compilation error: conversion from 'float' to non-scalar type 'String' requested编译错误:请求从“浮点”转换为非标量类型“字符串”

Thanks!谢谢!

Try尝试

float SpeedMPH = ((WindSpeed * 3600) / CONVERTMPH_FORMULA);
String WindSpeedMS = String(SpeedMPH,0); // 2nd param is decimal digits 

refer to Arduino String library as they stated that:请参阅Arduino 字符串库,因为他们指出:

Syntax句法

  • String(val)字符串(val)

  • String(val, base)字符串(val,基数)

  • String(val, decimalPlaces)字符串(val,decimalPlaces)

Parameters参数

  • val : a variable to format as a String. val :要格式化为字符串的变量。 Allowed data types: string, char, byte, int, long, unsigned int, unsigned long, float, double.允许的数据类型:string、char、byte、int、long、unsigned int、unsigned long、float、double。

  • base : (optional) the base in which to format an integral value. base :(可选)格式化整数值的基数。

  • decimalPlaces : only if val is float or double. decimalPlaces :仅当 val 为 float 或 double 时。 The desired decimal places.所需的小数位。

so instead of writing:所以不要写:

 String WindSpeedMS = WindSpeed;

you should write:你应该写:

String WindSpeedMS = String(WindSpeed, 5);

where 5 represents the number of decimal places desired, so if WindSpeed = 12.54545451 then WindSpeedMS = "12.54545"其中5表示所需的小数位数,因此如果WindSpeed = 12.54545451那么WindSpeedMS = "12.54545"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM