Reputation: 261
I am trying to divide a whole number by a decimal/float/double. I am able to divide whole numbers just find using: int Num1 = 300 / 2;
, but when I try to make that "2" a decimal it won't work. I have seen people mention doing this int Num1 = 300 / ((float)1.25);
. That honestly doesn't make any sense to me... I have also tried int Num1 = Decimal.Divide(300, 1.25);
without any luck..
Upvotes: 0
Views: 1462
Reputation: 12934
Simply put:
Upvotes: 2
Reputation: 149108
The problem is that you're trying to save the the result to an int
. Try this:
float result = 300 / (float)2;
float result = 300 / (float)1.25;
Or for more brevity (the f
is a signal to the compiler that this is a float
constant):
float result = 300 / 2f;
float result = 300 / 1.25f;
Note that float
is very different from a decimal
, and both have their advantages. To use a decimal:
decimal result = decimal.Divide(300, 1.25);
Or this (the m
is a signal to the compiler that this is a decimal
constant):
decimal result = decimal.Divide(300m, 1.25m);
Upvotes: 4
Reputation: 69392
An int
can only store whole numbers. When you divide a whole number by a decimal, the output will be a decimal (even if you use 4.00
because of the way floating points are stored).
This won't compile
int Num1 = 300 / ((float)1.25);
Even though you're casting an explicit float (otherwise 1.25 would be a double
), you're trying to store it in a variable of type int
. The compiler will not do this automatically because an implicit conversion doesn't exist for it to cast a float
as an int
for you. Therefore, you need to either tell the compiler that you don't mind losing the precision and cast it as an int
int Num1 = (int)(300 / ((float)1.25));
Or you can change the type of Num1
to be a float.
float Num1 = 300 / ((float)1.25);
Upvotes: 0
Reputation: 28747
You are trying to store the result in an integer. Instead use a double as the type of the variable to store the result:
double Num1 = 300 / 2;
double Num1 = 300 / 1.25;
Upvotes: 1