 # Problem with Long maths = (negval - negval)*100000

I'm currently working on a solution to my problem posted about printing floats.

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1259315604

So the problem I'm having is with this:

``````long temp3=(-10.282 - -10)*1000000;
``````

What I am trying to do is store the values in a float/decimal number with only the numbers after the decimal point. So for this example of --10.282 I would expect back -282.

Doing the calculation (-10.282 - -10)1000000 on a calculator would equal to *-282000**

Whilst Arduino calculates this as -19855

What's going on here. P.S I'm printing these values via Serial.print. Thanks in advance.

Can you try the following generic implementation.

I haven't actually run this code but I believe that the int casting should work fine.

``````#define DECIMAL_POINTS 1000000

long output_val = (number - (int)number) * DECIMAL_POINTS;
``````

I'm not sure what your problem is...

``````void setup()
{
Serial.begin(115200);
long temp3=(-10.282 - -10)*1000000;
Serial.println(temp3);
}

void loop()
{
}
``````

Output...

``````-281999
``````

Run on an Arduino Mega.

@FusiveResonance
Thanks but I tried your code with int casting and it doesn’t seem to work either. The value I get is the same which is -19855

@Mitch_CA

The answer I am expecting is

``````Output: -282000
``````

Floating point numbers are not exact, and may yield strange results when compared. For example 6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference between the numbers is less than some small number.

C:\Program Files (x86)\Arduino\reference\Float.html

@eried Thanks. Is there a way around this?

I'm not too sure what it means by checking the absolute value of the difference.

Instead of checking for equality, you need to check for "almost equality, so rather than saying:`if (myfloat == 1.0)`You should say something like:`if (abs(myfloat - 1.0) < 0.0001)`

You originally posted that the result was -19855.

A result of -281999 is correct for floating point math done with a 32-bit variable (the case for a double declared in the Arduino environment).

You cannot get around this without increasing the precision of the "double" variable type (say to 64-bit), because when "10.282" is stored in registry for operation it gets approximated; as 10.281999 it would seem.

I've posted this before, but it's a great paper... "What Every Computer Scientist Should Know About Floating-Point Arithmetic" http://docs.sun.com/source/806-3568/ncg_goldberg.html

3en: Can you post your whole sketch. It works fine for me:

``````  long temp3=(-10.282 - -10)*1000000;

Serial.println(temp3);
``````

yields:\

``````-281999
``````