Jake Sankey
Jake Sankey

Reputation: 5137

Returning a number less than 1

I am working on an app that needs to utilize a ratio of a given number and multiply that ratio times another number. Problem is that I can't get numbers less that 1 to give me the proper decimal ratio, instead it gives me zero (when it should be .5).

Example:

float number = 1/2; // This gives me zero
double number = 1/2; // This also gives me zero

Upvotes: 3

Views: 299

Answers (2)

Matt Lacey
Matt Lacey

Reputation: 8255

If you don't specify decimal places you're using integers which means the calculation is performed with integer precision before the result is cast to the type on the LHS. You want to do the the following when using hard coded numbers in your code:

float number = 1.0f / 2.0f;
double number = 1.0 / 2.0;

If you're aiming to use integer variables for an operation, you'll want to cast them to the type that you want for your result.

Upvotes: 6

PengOne
PengOne

Reputation: 48398

Try this

float number = 1.0/2.0;

Remember that 1 is an int, so you are essentially taking

(int)1 / (int)2

which returns

(int)0

To cast variables that are ints, do

float number = (float)numerator / (float)denominator;

Upvotes: 4

Related Questions