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

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

    so here would be my revised 'considered' answer...

    as we don't know what 'type' of variable is arriving as the numerator, we'd have to use the Double.TryParse on that. In the lab, we could cook something like this up:

    var numerator = "5"; // let's make it string to prove the point
    double parsedNumerator;
    int denominator = 100; // this could well be a constant
    
    double result;
    if(Double.TryParse(numerator, out parsedNumerator))
    {
        // notice no casting or convert fluff
        result = parsedNumerator/denominator;
        // do something with the result
    }
    else
    {
        // warn that the numerator is doo-lallie
    }
    

    now hiding under the desk - just in case i've overlooked something else obvious!! :)

    jim

提交回复
热议问题