Hello, I need help with printing decimals on an LCD. I know "lcd.print(variable,2)" will print 2 decimals but is there a way to only print necessary decimals? For example if the variable:
1.00, then I want to print 1
1.20 then I want to print 1.2
1.22 then I want to print 1.22
I basically want the effect of "printf("%g",variable)" for LCDs.
Is it possible to do this? If yes, please let me know, thank you!
Edit:
If it is possible, it would be appreciated if you show me how.
Of course it's possible. And easy, as well. Study the documentation for printing to the LCD or printing to anything. There is a second parameter you can supply that sets the decimal point to print. The default is two decimal places. For your program, the parameter is a zero.
I mean test the float you are printing for the range of values that would give you a zero as the first decimal and print it with a zero parameter. If greater than that, test for the next range that will give you a single digit decimal and print with a 1 parameter, and continue with other ranges and parameters.
void printFloat(Stream &s, float a)
{
int i = (int)a; // the integer part
float f = a - i; // the fraction
int d100 = (int)(f * 100); //
if (d100 == 0) s.print(a, 0); // x.00
else if (d100 % 10 == 0) s.print(a, 1); // x.y0
else s.print(a, 2); // x.yz
}
void setup() {
Serial.begin(115200);
float a = -12.345;
printFloat(Serial, a);
Serial.println(); // only for Serial, to jump to the next line
a = -12.30;
printFloat(Serial, a);
Serial.println();
a = -12.0;
printFloat(Serial, a);
//printFloat(lcd, a); // should work if you have a lcd object
}
void loop() {
// put your main code here, to run repeatedly:
}
will print:
-12.35
-12.3
-12
and you can hand over a lcd object instead of the Serial also.
Use dtostrf, then go to the end of the c-string and decrease position while the character is a '0', then put a '\0' on the next position, to mark the end of the c-string