Why returns C# Convert.ToDouble(5/100) 0.0 and not 0.05

前端 未结 7 1825
深忆病人
深忆病人 2020-12-06 18:52
double variable = Convert.ToDouble(5/100);

Will return 0.0 but i expected 0.05

What can / must i change to get 0.05

because the 5 i

7条回答
  •  旧巷少年郎
    2020-12-06 19:16

    5/100 is done in integer arithmetic, which yields 0 before conversion. Try

    double variable = 5.0/100;
    

    If 5 is in a variable x (of integer type), then use:

    variable = (double)x/100; 
    

    or

    variable = ((double)x)/100;
    

    to make the intent clear (thanks John!)

    or

    variable = x/100.0;
    

提交回复
热议问题