Parsefloat not showing after decimal point after addition

Hello, well, I'm now retired and want to keep my brain as active as possible and thought arduino programming and circuit building was a good way to go. Anyway, I've got some books and looked on the web and I've had a go at writing a program to use the Serial monitor as an input/output screen. All is working fine when I use integers (int) but as soon as I try to use a float the output isn't showing correctly.
Here's my code. (Hope i'm doing this right)

float number1;
float number2;
float Pass_number;
float answer;
float action;

void setup() {
  Serial.begin(9600);
}

void loop() {
Serial.println("Enter your first number");
while (Serial.available()==0){}
number1=Serial.parseFloat();Serial.print("The first number is ");Serial.println(number1);
while (Serial.available()!=0){Pass_number=Serial.parseFloat(); }
Serial.println("Enter your second number");
while (Serial.available()==0){}
number2=Serial.parseFloat();Serial.print("The second number is ");Serial.println(number2);
while (Serial.available()!=0){Pass_number=Serial.parseFloat(); }
Serial.println("Select what you want to do");
Serial.println(" 1 add, 2 subtract, 3 multiply, 4 divide");
while (Serial.available()==0){}
action=Serial.parseFloat();
Serial.print("The answer is: ");
while (Serial.available()!=0){(Pass_number)=Serial.parseFloat(); }
if (action==1){answer = number1+number2;}
if (action==2){answer = number1-number2;}
if (action==3){answer = number1*number2;}
if (action==4){answer = number1/number2;}
Serial.print(answer, 2);
exit(0);//ends loop
}

This is what I get as an output.

code output

I know the numbers after the decimal are being used because the output rounds up or down depending on whether its above or below .5
I suspect its in the 'pass_number' variable but I'm not certain how to solve it. Any ideas?
Thanks.

You are comparing "action" to 1, 2, 3, or 4. You should make "action" an 'int' (not float) variable and use Serial.parseInt();

Hi, thanks for the quick reply. I tried that but I still don't get anything after the decimal point.

Try putting Serial.flush(); before exit(0);
I've never tried using exit() to try and stop a sketch, but it may be freezing the code before there is time to complete sending the serial data.

YAYY! That worked! Thank you both for your quick advice.

if you only want something to run once, better to put it in setup() instead of loop(), and leave that exit(0) out completely. Don't think I've ever seen that used before.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.