Real simple: I print a float and I am expecting to get the 2 decimals correctly and disregard the rest.
instead I get a round up version. Right?
Code is
Serial.println (Uptime_Hrs, 2);
Serial.println (Uptime_Hrs, 4);
Gets me:
0.01
0.0075
I would want the top number not to change to one hundredth till the actual value exceeds 0.01
Please help, Thanks
That is how Serial.print() works.
guix
March 12, 2023, 10:22pm
4
f = 0.0099
f * 100 = 0.99
floor( f * 100 ) = 0.00
floor( f * 100 ) / 100 = 0.00
f = 0.0100
f * 100 = 1.00
floor( f * 100 ) = 1.00
floor( f * 100 ) / 100 = 0.01
Try:
Serial.println (Uptime_Hrs-0.005, 2);
This will un-do the 'round to the nearest 0.01' that print does.
John
thanks that worked, but the first few readings are weird. Negative Zero....?
I can't deliver this project like this, I would need a 0.00
Look
-0.00
0.0039
Downtime Seconds: 15
CumulatedUpTimeSec: 14 DOWN_TimeSec 0
30
-0.00
0.0042
Downtime Seconds: 15
CumulatedUpTimeSec: 15 DOWN_TimeSec 0
31
-0.00
0.0044
Downtime Seconds: 15
CumulatedUpTimeSec: 16 DOWN_TimeSec 0
32
-0.00
0.0047
Downtime Seconds: 15
CumulatedUpTimeSec: 17 DOWN_TimeSec 0
33
0.00
0.0050
Downtime Seconds: 15
CumulatedUpTimeSec: 18 DOWN_TimeSec 0
34
0.00
0.0053
laptophead:
Negative Zero....?
No, a negative number, closer to zero than -0.005.
I kinda figured something, not elegant but the best I got.
String str2 = String(Uptime_Hrs, 4);
Serial.print ("Uptime_Hrs-string Original : "); Serial.println (str2);
int str2_LENGHT = str2.length();
Serial.print ("str2_LENGHT: "); Serial.println (str2_LENGHT);
str2.remove(str2_LENGHT-2, 2);
This actually works.
I don't know why the String(Uptime_Hrs, 2); still does the rounding.
So I had to generate a 6 digit string...etc
Hope others will figure something easier...
Thanks
MITCH
guix
March 13, 2023, 9:15am
9
Did you try floor( f * 100 ) / 100 as suggested in reply #4 ?
Sorry. Try this:
if (Uptime_Hrs >= 0.005)
Serial.println (Uptime_Hrs-0.005, 2);
else
Serial.println (0.00, 2);
Thanks a lot everyone. Problem Solved
John,
I just made it an absolute number, it works.
Serial.println (abs (Uptime_Hrs-0.005), 2);