# Newbie question on int, float, cast

What happens if a variable is declared using the int function, but the value calculated is fractional? Is it truncated at the decimal point? or will the variable overflow?

Ex: A potentiometer value is read ranging 0-1023, then divided by four to get something in the 0-255 range. 1023/4 = 255.75. Will int store 255 or overflow and give inconsistent results?

Should the scaled variable be stored as a float (since it's possibly fractional), then cast to an int?? Or is that step unnecessary??

This seems like a really basic question, but i'm having an trouble finding (or possibly understanding) the answer.

What happens if a variable is declared using the int function, but the value calculated is fractional? Is it truncated at the decimal point? or will the variable overflow?

You have the means to test this yourself so why not try it and see ?

ints are declared to be of type int, no function is involved, you just tell the compiler what sort it should be.

On the Uno etc an int is 16 bit signed value internally, it can only ever hold integer values in
the range -32768 to +32767. Any time the variable is updated an integer in that range is put there.
Conversions will be done if necessary.

In C 1023/4 = 255, since integer division leads to an integer result.
1023.0/4.0 will give 255.75, a float, but storing that in an int variable will truncate to 255 anyway.

UKHeliBob:
You have the means to test this yourself so why not try it and see ?

Well, I guess that's one way HeliBob (no sarcasm intended)

MarkT:
In C 1023/4 = 255, since integer division leads to an integer result.
1023.0/4.0 will give 255.75, a float, but storing that in an int variable will truncate to 255 anyway.

Thanks Mark! This is the bit of info i guess i didn't fully understand.

-Mo

Thanks Mark! This is the bit of info i guess i didn't fully understand.

The following is the illustration of what MarkT has precisely and accurately briefed in Post #2:

If you divide one integer number by another integer number using C instructions, you will be able to catch only the quotient (because it is an integer); you will not be able to catch the remainder (as it is not an integer) and it will be lost. Similar reasoning could be put forward for the division of the floating point numbers. Let us see the following examples:

``````Serial.begin(9600);
int x = 1023;
int y = 4;
int z = x/y;        // Manual result = 255.75
Serial.println(z);  // you will get 255 and not 255.75 because of integer division

float z1 = x/y;
Serial.println(z1);  //you will get 255.00 and not 255.75 because of integer division

float x1 = 1023.0;
float y1 = 4.0;
float z2 = x1/y1;
Serial.println(z2);   //you will get 255.75 because of float division

int z3 = x1/y1;
Serial.println(z3);   //you will get 255 and not 255.75 because of storage type even though the division is floating
``````