0

The question might be stupid, but I have no idea why is this happening. Here's the problem: I got double someDouble = (39 * 10) / 100; and I get someDouble = 3.0, instead of 3.9. I just have no damn clue why is this, help please ?

Martin Dzhonov
  • 1,021
  • 4
  • 15
  • 28

7 Answers7

7

Because when you multiply integer to integer and divide to integer - you get an integer.

Which is implicitly casted to double after it was calculated.

zerkms
  • 249,484
  • 69
  • 436
  • 539
4

Because what you done is here integer division. .NET has 3 type of division. From 7.7.2 Division operator

  • Integer division
  • Floating-point division
  • Decimal division

Integer division:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands.

You can use one of these;

double d = (39 * 10) / 100d
double d = (39d * 10d) / 100d
double d = (double)(39 * 10) / 100
MichaC
  • 13,104
  • 2
  • 44
  • 56
3

Make it

double someDouble = (39.0 * 10.0) / 100.0;
Ryan Schlueter
  • 2,223
  • 2
  • 13
  • 19
3

It's because you are doing integer division:

double someDouble = (39 * 10) / 100;

If you want to do floating point division then at least one of the operands needs to be a double:

double someDouble = (39 * 10) / 100.0;
ChrisF
  • 134,786
  • 31
  • 255
  • 325
3

Another one solution

double someDouble = ((double)39 * 10) / 100;
Dmytro Rudenko
  • 2,524
  • 2
  • 13
  • 22
2

that's a normal behavior try this please just for clarification There are three types of division operators

    Integer division
    Floating-point division
    Decimal division

In your case we have Integer division,and the compiler will treat this as integer as it fast and simple operation while simple precision or double precision operation are (double, float, decimal in .net ) quite complex and cpu ant time consuming as stated in wikipedia take a look here http://en.wikipedia.org/wiki/Floating_point#Multiplication_and_division to understand more what means

  double someDouble = (39f * 10f) / 100f;   

hope this help

BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
0

All three values in your expression are integers. 39 * 10 is an integer as well. So is 100. Dividing the integer 390 by the integer 100 yields 3 just as you'd expect it to. That then gets cast to float.

Further, the optimizer will evaluate that constant expression at compile time and simple change the generate IL to the equivalent of

double someDouble = 3 ;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135