0

I have a LCD that displays a float variable. I would like to show a comma instead of a dot as the decimal separator.

float temp = 23.50;
lcd.setCursor(0, 0);
lcd.print(temp);

I want to show 23,50 instead of 23.50.

Is there any function to convert or format it?

2

Print the integer part, print a comma, then print the value minus the integer part.

float value = 123.45;
int ival = (int)value;
int frac = (value - ival) * 100;

Serial.print(ival);
Serial.print(",");
if (frac < 10) Serial.print("0");
Serial.println(frac);
2

May be overkill for this simple usage but, if you are printing numbers in more than one place in your program, it may be convenient to implement a filter that replaces all dots with commas.

Here is one such filter:

// Replace dots with commas.
class CommaForDot : public Print
{
public:
    CommaForDot(Print &downstream) : downstream(downstream) {}
    virtual size_t write(uint8_t c) {
        return downstream.write(c=='.' ? ',' : c);  // replacement
    }
private:
    Print &downstream;
};

And here is a simple test:

void setup()
{
    Serial.begin(9600);
    float a = 12.34;

    Serial.print("Through Serial:      ");
    Serial.println(a);

    CommaForDot filteredSerial(Serial);
    Serial.print("Through CommaForDot: ");
    filteredSerial.println(a);
}

void loop(){}

The output is:

Through Serial:      12.34
Through CommaForDot: 12,34
1

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)

Demo

void setup() {
  Serial.begin(9600);
  while(!Serial);

  float a = 12.34;
  char buffer[] = "9999.99";
  dtostrf(a, 4, 2, buffer);
  char* p  = strchr(buffer, '.');
  *p = ',';
  Serial.println(buffer);
}

void loop() {

}

The strchr search for the first ocurrence of second arg ('.' in this case) and return a pointer to that char. You then use that pointer to sustitute '.' with ','.

You have the final string in buffer, where you can use it for whatever purpose you fancy.

Caution: You have to reserve space (buffer) to hold your biggest value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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