Ahmad Syafrudin
Ahmad Syafrudin

Reputation: 35

How to get decimal by long divide operation

long a = 50000;
long b = 98600000;

I have tried with

float c = a/b;
decimal c =a/b;
double c = a/b;

But all of them always get 0

How do I get the result (0.00507...)? Thanks.

Upvotes: 1

Views: 3095

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56433

When dividing two long types you will always get a long as a result regardless of whether the receiving type is of decimal, double or float.

to receive a decimal result:

decimal c = (decimal)a / b;

to receive a float result:

float c = (float)a / b;

to receive a double result:

double c = a * 1.0 / b;

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

You get 0 since the division takes place in integer arithmetic, irrespective of the type of the variable to which the expression is assigned.

To remedy, you can use

1.0 * a / b

for the double case,

1.0f * a / b

for the float case, and

1.0M * a / b

for the decimal case. There are other ways, but I find this approach clearest. The fact that you see a literal at the start of the terms signals to the reader of your code from the get-go that you know what you're doing.

The M denotes a decimal literal in C#. (And 1.0f denotes a float literal.) This technique forces the conversion of the a and b to the appropriate type for the division.

Finally, I'd avoid any expression that involves the implicit conversion of a long to a float.

Upvotes: 1

Sean
Sean

Reputation: 62492

You're diving a long by a long, which always yields a long. You need to cast one of the values:

float c = ((float)a)/b;
decimal c =((decimal)a)/b;
double c = ((double)a)/b;

Upvotes: 9

Related Questions