 # Floats and Long

I've been trying to figure out why doing these two sums results in something slightly different.
I found there something that "floats" can only show 7 digits or something like that, but I did not quite understand it, and it is something I need to know to make it work.

I need to do add two products that are at most 8 digits (An example: 11111111 and 22222222), the letter A has to be float (or something that can handle decimals in case something is recommended) and the letter B has to be a long.

Code:

long B = 11111111;
float A = 22222222;

void setup() {
Serial.begin(9600);
Serial.print(A += B);
//A = 33333332.00
//Expected: A = 33333333
}

void loop() {
}

Thanks!!!

The problem is that, as stated, you can't expect accuracy in the eigth digit of a number that is stored in four bytes. Arduino has a float, but double, which in most processors/languages would be eight bytes long, is just the same as float in Arduino. You are up against a limit that can't be changed.

jrdoner

And how do people do calculators with Arduino? They can have results greater than 8 digits and decimals.

Isn't there a way to enlarge the float or something?

What happens if you declare A as double instead of float? double can handle digits after the decimal point.

In these cases, it is often suggested that A be declared as a long but scaled by some value (say, by 1000). If you want to add something to A, first multiply it by 1000L. Then, A/1000 is the portion to the left of the decimal point, and A%1000 is the portion to the right of the decimal point. If A%1000 is less than 100, you are going to have to print one or two leading zeroes. All of this can work if A is non-negative; I don't know what happens if A is negative.

On the Arduino Due, doubles have 8-byte (64 bit) precision.

• from the Arduino Reference

The OP has not specified the processor, so double might or might not work.

And how do people do calculators with Arduino?

You can do arbitrary precision calculations on the Arduino, if you stay away from standard variables like float and long. Check out the BigNumber library.

Some approaches use digits stored in a character array.