Click here to Skip to main content
15,936,349 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is a short code snippet that I am having trouble with:

C#
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
    int k = DepthOfDischarge.SelectedIndex;
    double DoD = DoD = 10 / (k + 1);
    //MessageBox.Show(DoD.ToString());
    return (DoD);
}


The combobox has 10 items: 10%, 20%, ... , 90%, 100%.
Now if I select say the third item (30%) in the combobox, the DoD variable stores 3 and not 3.33333333...
If I select say the 7th item, (70%) in the combobox, then the DoD reads 1 and not 1.42857...

The decimal seems to be truncated. Why is this happening in a 'double' or 'decimal' data type?
Am I missing something important?
Posted
Updated 30-Jan-12 1:09am
v3

Use floating-point values instead of integers:
C#
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
    double k = Convert.ToDouble(DepthOfDischarge.SelectedIndex);
    double DoD = 10.0 / (k + 1.0);
    //MessageBox.Show(DoD.ToString());
    return (DoD);
}
 
Share this answer
 
Comments
Winston_D 30-Jan-12 7:13am    
It works like you suggested but why does a simple integer not work like expected?
CRDave1988 30-Jan-12 7:15am    
because the rule of exp is that if all element r int than result will be int
Winston_D 30-Jan-12 7:16am    
Thnx a million. I'll keep it in mind for next time
Try using double DoD = DoD = 10.0 / (k + 1.0);
 
Share this answer
 
C#
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
    Double k = cdbl(DepthOfDischarge.SelectedIndex);
    Double DoD = 10.0 / (k + 1.0);
    //MessageBox.Show(DoD.ToString());
    return (DoD);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900