7

If I divide 150 by 100, I should get 1.5. But I am getting 1.0 when I divided like I did below:

double result = 150 / 100;

Can anyone tell me how to get 1.5?

alex
  • 6,818
  • 9
  • 52
  • 103
Irannabi
  • 129
  • 1
  • 4
  • 15

5 Answers5

17

try:

 double result = (double)150/100;

When you are performing the division as before:

double result = 150/100;

The devision is first done as an Int and then it gets cast as a double hence you get 1.0, you need to have a double in the equation for it to divide as a double.

Heinrich
  • 2,144
  • 3
  • 23
  • 39
10

Cast one of the ints to a floating point type. You should look into the difference between decimal and double and decide which you want, but to use double:

double result = (double)150 / 100;
MattW
  • 4,480
  • 1
  • 12
  • 11
5

Make the number float

var result = 150/100f

or you can make any of number to float by adding .0:

double result=150.0/100

or

double result=150/100.0
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
Mayank
  • 8,777
  • 4
  • 35
  • 60
  • Note that adding the `.0` technically makes it a double which won't fit in a `float` (your code shows that but the text contradicts it). – Basic Sep 28 '19 at 20:17
4
double result = (150.0/100.0)

One or both numbers should be a float/double on the right hand side of =

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
2

If you're just using literal values like 150 and 100, C# is going to treat them as integers, and integer math always "rounds down". You can add a flag like "f" for float or "m" for decimal to not get integer math. So for example result = 150m/100m will give you a different answer than result = 150/100.

Jason Whitish
  • 1,428
  • 1
  • 23
  • 27