# Thread: Convert float to int?

1. ## Convert float to int?

Can anyone explain how this is done.

I am importing a couple values from a class and trying to divide them to get a fractional output from two int variables. I currently get a 0 for a and b when I divide. None of the variables are zero.

Code:
```Rational operator < (Rational c)// compares two fractions <
{
float a = (numerator / denominator);
float b = c.numerator / c.denominator;
if (a < b)
{
truth = 0;
return truth;
}

else
truth = 1;
return truth;

}```

2. Use double instead of float to have more breathing room (aka more precision).

3. So, numerator and denominator are ints? You would need to cast them before you perform the division.

4. Ive never heard of cast. I'm not using constants so I'm not sure how const_cast would help.

5. Code:
`float a = (static_cast<float>(numerator) / static_cast<float>(denominator));`

6. Found an easier way to do it.

float x,y,z;

x = someIntVariable;
y = someOtherIntVariable;

z = x/y;

7. Let me try this again...

If you have the choice avoid float. Use double.

8. Actually in the real code I did. I just got a little too quick with my keyboard....my bad.

9. You might want to make sure the denominator isn't zero before you go dividing by it.

And you don't have to use
Code:
```truth = 0;
return truth;```
you can use
Code:
`return 0;`
unless you use truth elsewhere.

10. Originally Posted by dwks
And you don't have to use
Code:
```truth = 0;
return truth;```
you can use
Code:
`return 0;`
unless you use truth elsewhere.
Also, isn't the return value inverted. 1 is normally true is C/C++, init?

Unless you particularly want truth to defy convention it would be better to have
Code:
`          return a<b;`

11. Originally Posted by kryonik
Found an easier way to do it.
float x,y,z;

x = someIntVariable;
y = someOtherIntVariable;

z = x/y;
If you're going to do that, you might as well do this:
Code:
```float a = numerator;
a = a / demoninator;```

12. Or this:
Code:
```double double_value(double numerator, double denominator) {
return numerator / denominator;
}

int x = 1, y = 3;
double number = double_value(x, y);```
Personally I don't see anything wrong with a cast. If laserlight's code
Code:
`float a = (static_cast<float>(numerator) / static_cast<float>(denominator));`
is too long for your taste, you can cast only one variable (as swoopy's code relys on):
Code:
`float a = (static_cast<float>(numerator) / (denominator));`
If that's still too long you could use a C-style cast (which probably isn't a good idea):
Code:
`float a = (float)numerator / denominator;`