The default number of float fraction issue

dears,

i have written complex function and i have used the float number and multiplied of of the numbers, but the float number use only the 1st 2 fraction, so how can i use all fraction of float number.

i have simple program and the result, i hope this to be clear to my question:

void setup(){

Serial.begin(9600);

float f=10.123456789;
Serial.println(f);

int i= (int) f * 10000000;
Serial.println(i);
}

void loop(){
}

the result as the following:

10.12 // not 10.123456789
1012 // not 101234567

thanks.

you are overflowing an int

int i= (int) f * 10000000;

that is a big number

and Serial.println() by default prints two decimal places on a float. If you want more, use this format where I have selected six decimal places:

  float f=10.123456789;
  Serial.println(f, 6);

FYI, floats have only about 6 decimal places of precision so don't be surprised at the result of this:

  float f=10.123456789;
  Serial.println(f, 9);

Thanks on your reply.

this is as example, but the actual thing is why the float ignore the other fraction??
when float f=10.123456;
why the result of int i= (int) f * 1000; is not 10123 ???

thanks.

When you use the Serial object to print a float, it defaults to 2 decimal places. I think you can use:

float val = 1.2345678;

Serial.print(val, 5);     // Show 5 decimal places.

Dear

i don't want to print, i want to process the float number !!

i need to dial with the float result [int i= (int) f * 1000;] i value;

thanks

Looks like we double-posted. To answer your question about why the expression

int i= (int) f * 1000;

doesn't work, the order of precedence of operators means that f is cast to an int before it's multiplied. You need to force the multiplication with parentheses first:

int i= (int) (f * 1000);

or even:

int i= (int) (f * 1000.0);

so later on you remember you were forcing float math and then casting it to an integer.

or just

int i= f * 1000;

the assignment does the cast too

more useful might be

int i= round(f * 1000.0);

which does proper rounding instead of truncating

beware that an int is only 16 bits for the Arduino UNO/MEGA so max value is about +-16383

use long for 32 bit.

@robtillaart: I'm not a big fan of expressions like:

int i= f * 1000;
int i= round(f * 1000.0);

because both rely on "silent casts" to work correctly. While the code compiles without error, it's dangerous because you're trying to pour 4 bytes of data into a 2-byte bucket. The compiler my company produced had a "picky flag" that could be set from 1 to 10. Level 10 was as fussy as the Lint utility on Unix and the code above would not pass without error. Using an explicit cast at least better documents what you are doing:

int i= (int) (f * 1000.0);
int i= (int) round(f * 1000.0);

@econjack
agree, silent casts are not so good practice