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

前端 未结 7 1811
深忆病人
深忆病人 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:22

    Marco,

    try this instead:

    double variable = Convert.ToDouble((double)5/100);
    

    jim

    [late edit] - as was pointed out (by silent voters :)) the use of the Convert is redunant. It should obviously be done in a fashion similar to the other entries. I acknowledge that but leave it in above as an example of how to get quickly downvoted when answering a question in a hurry... let caution be your master!!

    Also, as we don't know whether the variable will come from a string or a number, he should also consider tryparse etc on the number 1st before doing the arithmetic.

    0 讨论(0)
提交回复
热议问题