Problems Casting Float to Int

I am new to the cast function in Arduino, but it looks pretty straight forward and I needed to truncate numbers for my use.

I have tried a number of different things to try and get the returned numbers to be as expected, but thus far have not made too much progress, other than having a decent list of things that don’t work.

So this is what the code is suppose to do.

  1. I have a variable called fader, it counts down from 254 to 50 by 2s and then counts back up to 254 by 2s. I have this working.

  2. The fader variable is applied to a float variable through a math function. I want my original number (float r1, g1, b1) to be multiplied by a fraction (fader/255). I have this outputting to a float (float or3, og3, ob3)

  3. Finally I want to cast this float to an int as I need whole numbers. So I want to cast the float variables or3, og3 and ob3 to int variables r3, g3 and b3. The truncation is fine, I don’t necessarily need it rounded.

At this point, I can not get the code to output what I am expecting. I know something is coded wrong, but I am having problems pinpointing the issue. I suspect its something relatively simple that I overlooked but any input would be greatly appreciated.

int fader = 254;
boolean fade = true;

float r1 = 0;
float g1 = 0;
float b1 = 255;

float r2 = 0;
float g2 = 255;
float b2 = 0;

float or3 = 0;
float og3 = 0;
float ob3 = 0;

float or4 = 0;
float og4 = 0;
float ob4 = 0;

int r3 = 0;
int g3 = 0;
int b3 = 0;

int r4 = 0;
int g4 = 0;
int b4 = 0;


void setup() {
  
r3 = r1;
g3 = g1;
b3 = b1;

r4 = r2;
g4 = g2;
b4 = b2;

Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

Serial.print(or3);
Serial.print("   ");
Serial.print(og3);
Serial.print("   ");
Serial.print(ob3);
Serial.print("     ");
Serial.println(fader);


if(fader == 50){
  fade = !fade;
}
if(fader == 254){
  fade = !fade;
}


if(fade == true){
  if(fader > 50){
    if(r1 != 0){
      or3 = (r1 * (fader/255));
      r3 = (int) or3;
    }
    if(g1 != 0){
      og3 = (g1 * (fader/255));
      g3 = (int) og3;
    }
    if(b1 != 0){
      ob3 = (b1 * (fader/255));
      b3 = (int) ob3;
    }
 
  fader = fader-2;
  }
}
if(fade == false){
  if(fader < 254){
if(r1 != 0){
      or3 = (r1 * (fader/255));
      r3 = (int) or3;
    }
    if(g1 != 0){
      og3 = (g1 * (fader/255));
      g3 = (int) og3;
    }
    if(b1 != 0){
      ob3 = (b1 * (fader/255));
      b3 = (int) ob3;
    }
 
  fader = fader+2;
  }
}
}

ClncyFshSlayer: ... a fraction (fader/255) ...

That ain't no fraction.

(float)(fader/255.0) is a fraction.

And, just like that it works great! I figured it was something simple, and it was. Thanks!

I figured it was something simple, and it was.

On the other hand, that snippet of code is NOT casting a float to an int.