ittoop
December 20, 2022, 11:55am
1
Dear All,
When I am trying to convert a string ( "1000.01" ) to a floating pointumber and multiply the value by 100. I get the output as below. I am using Arduino Mega2560 board with Arduino IDE version 1.8.19. My code is given at the end of this post.
Output:
dummy_float:1000.01
dummy:100000
If I repeat this with another string in the atof function the output was as shown below. The code is attached for your kind reference. Please help.
Case1:
String : "1000.02"
dummy_float:1000.02
dummy:100001
Case2:
String : "1000.03"
dummy_float:1000.03
dummy:100003
Code:
#include <stdio.h>
#include <stdlib.h>
void setup() {
unsigned long dummy;
float dummy_float;
Serial.begin(9600);
dummy_float=atof("1000.01");
dummy=(float)dummy_float*100.0;
Serial.print("\n");
Serial.print(dummy_float);
Serial.print("\n");
Serial.print(dummy);
}
void loop() {
}
Can you say what it is that is "strange"?
Perhaps you want:
dummy = uint32_t (dummy_float*100.0);
Or does that yield the same result?
Hi,
Floating point numbers may not be exactly what you see.
Try this code and see the result:
#include <stdio.h>
#include <stdlib.h>
void setup() {
unsigned long dummy;
float dummy_float;
Serial.begin(9600);
dummy_float=atof("1000.01");
dummy=(float)dummy_float*10000.0;
Serial.print("\n");
Serial.print(dummy_float,6);
Serial.print("\n");
Serial.print(dummy);
}
void loop() {
}
1000.009948
10000099
type or paste code here
ittoop
December 20, 2022, 4:53pm
5
Thank you all for your fast reply.
ruilviana's solution worked.
Since I need only two decimal places I have modified the line as follows.
dummy=(dummy_float+0.001)*100.0;
Modified code:
#include <stdio.h>
#include <stdlib.h>
void setup() {
unsigned long dummy;
float dummy_float;
Serial.begin(9600);
dummy_float=atof("1000.01");
dummy=(dummy_float+0.001)*100.0;
Serial.print("\n");
Serial.print(dummy_float);
Serial.print("\n");
Serial.print(dummy);
}
void loop() {
}
system
Closed
June 18, 2023, 4:53pm
6
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.