c# - Convert Double Value ToString() -


this question has answer here:

may i'm asking silly question don't understand why doesn't give me output expect (i.e 2.5):

double x = 5/2; console.writeline(x.tostring()); 

.net fiddle

5 / 2 performs integer division no matter type assign it. disregards fractional part.

you need use floating-point division instead.

double x = 5.0 / 2; double x = 5 / 2.0; double x = 5.0 / 2.0; 

from / operator

when divide 2 integers, result always integer. example, result of 7 / 3 2.

from c# specification part $7.7.2 division operator, there 3 types of division;

  • integer division
  • floating-point division
  • decimal division

and relevant part in integer division;

the division rounds result towards zero, , absolute value of result largest possible integer less absolute value of quotient of 2 operands. result 0 or positive when 2 operands have same sign , 0 or negative when 2 operands have opposite signs.


Comments