-10

I tried this expression 12/13 in c# and I got value as 1 When I cast the value to double then actual value is coming.

Can someone explain me why this is happening?

Thanks Ajit

Ajit
  • 11
  • 3

3 Answers3

3

It is because of Integer Division. Because both of your values are Integers, the result will be an integer as well.

You could do a *1.0 to force a double whenever you do a calculation, and it also doesnt change the solution.

BotMaster3000
  • 472
  • 4
  • 16
  • 3
    Instead of `* 1.0`, a more *readable* choice is to use either suffix `12d` or fractional part `12.0` – Dmitry Bychenko May 24 '18 at 11:19
  • @DmitryBychenko yes of course, but if you are working with integer-variables, it will be hard to do so. For hardcoded numbers your approach of course is more readable – BotMaster3000 May 24 '18 at 11:39
1

The value of 12/13 is smaller than 1, which means that due to integer trunctaion it will truncated to 0.

Codor
  • 17,447
  • 9
  • 29
  • 56
  • 1
    "rounded" is not the correct word to use here. If use this word then it means 3.6 will rounded to 4 which is false. – CodeNotFound May 24 '18 at 11:16
  • I changed the answer as indeed the explanation might have been misleading. However, according to [this](https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero) Wikipedia article, _rounding_ can refer to various operations which replace one value by possibly another one. – Codor May 24 '18 at 11:19
  • Indeed but the correct expression (based on the link who use on your comment) wiil be _rounding down_. – CodeNotFound May 24 '18 at 11:21
0

Any operation with integer results answer in integer. any operation with double results answer in double. That is default to change scenario you need to cast so that you can get result per your need.