0

I feel it's a bug, is it?

decimal s = 30 / 9;
double w = 20 / 9;
Console.WriteLine(s);
Console.WriteLine(w);

and the result is

enter image description here

regestea23
  • 456
  • 6
  • 19
  • 3
    It is the default behavior in all .net versions, *integer division*: `30 / 9 == 3; 30 % 9 == 3` (here `%` stands for remainder), if you want *decimal*, put it as `30m / 9m`, in case of `double` - `20.0 / 9.0` – Dmitry Bychenko Jan 02 '22 at 11:31

1 Answers1

5

Is this normal, yes. Is this a bug, no.

You're doing integer math on 30 / 9 which is 3 and then assigning to a decimal which then does the conversion. Same with the second line.

Try this instead:

decimal s = 30m / 9m;
double w = 20.0 / 9.0;
Console.WriteLine(s);
Console.WriteLine(w);

That gives:

3.3333333333333333333333333333
2.2222222222222223

You need to declare your constants in your expression with the correct type. Suffix an m for decimal. And either provide a decimal place or suffix with a d for double.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172