Can some one please help explaining the output if serial monitor

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

void loop()
{
  //float data=56.78; 
  float data=56.78; 
  int data1 = (int)data;
  //Get the integer
  int data2 = (int)((data - data1) * 100); // For two decimal points

  Serial.print (data);
  Serial.print ("\n");
  Serial.print(data1);
    Serial.print ("\n");
  Serial.print (data2);
    Serial.print ("\n");  Serial.print ("\n");

  delay(1000);
}

And the output is

56.78
56
77

56.78
56
77

56.78
56
77

Whereas what I expect is

56.78
56
78

56.78
56
78

56.78
56
78

If I change data to be equal to 56.79 I get expected output

56.79
56
79

56.79
56
79

Thanks

It is due to the precision of float.

maybe just recalculate your formulae to just use ints

int data=5678;
int data1 = data / 100;

Serial.println ( float( data ) / 100.0f );
Serial.println ( data1 );
Serial.println ( data - ( data1 * 100 )  );

Output

56.78 56 78

Just round the answer.

int data2 = (int)((data - data1) * 100 + 0.5);

Pete

Hello el_supremo

I did what you suggested and that works for me. Thank you very much
I was trying to write this sample code to separate integer part and decimal part.

But I just wanted to understand why it works.

As it was pointed out that this is happening due to precision of float.
But now the statement is evaluated to (when data =56.78)

int data 2 = int (77.5) [ because earlier data2 was 77)
and we get 78.

But It was not very clear to me that what my code was fine in one case and giving unexpected output in another.

Thanks

Some decimal fractions can't be exactly represented in binary. For example, this code prints 56.78 to 6 decimal places:

float data=56.78;
void setup(void)
{
  Serial.begin(9600);
  Serial.println(data,6);  
}

void loop(void) {}

and it prints this: 56.779998

When you subtract 56 and multiply by 100 you get 77.9998 and converting to an integer only gives you 77. Adding .5 to this before converting to an integer rounds the result to the nearest integer.

Pete