1

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?

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Nov 20, 2017 at 13:12

3 Answers 3

3

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);
answered Nov 20, 2017 at 13:21
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.

answered Nov 20, 2017 at 13:28
1

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
answered Nov 20, 2017 at 13:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.