float precision problem

hello i'm using an UNO and I wrote a Sketch with a void loop like this :

(tim is an unsigned long and var is a float)

void loop()
{
tim = pulseIn(8, HIGH, 2000000);
var = tim/1000000;
Serial.println(var);
}

the problem is that it only displays 0.00 , 1.00 when it's 0.52 or 1.2 for example.

How could i fix that ?

thanks.

aboglio:
How could i fix that ?

Do division with a floating point number.

var = tim/1000000.0;

Welcome to the Forum. Make sure you read the two posts by Nick Gammon at the top of the Forum, especially about using code tags when posting code.

Your problem is that the compiler does not know the math is supposed to be done using floating point. To so inform it, use the following:

  unsigned long tim;
  float var;
  
  tim = 520000L;
  var = tim/1000000.0;
  Serial.println(var);

Note the decimal notation in the divide expression. That forces the expression evaluation to be done in floating point. Personally, I would use:

var = ( (float) tim) / 1000000.0;

to better document your intentions.

thank you very much !!

But remember, floats are evil! They are slow, inaccurate and you almost never need it (and I hate the fact all Arduino tutorials seem to use it. :frowning:

See a nice explanation of Delta_G here.