Possible Loss of Fraction in C#
I had written some code in C# to try to account for possible fractions that looked something like this:
double columnCountDividedBy2 = numberOfColumns / 2;
In the above example, numberOfColumns is declared as an int. I thought that, because I was assigning the result to a double, I would get a fractional number if numberOfColumns divided by 2 was not a whole number. However, what was happening was that the fraction was being dropped. ReSharper was also giving me a warning message, "possible loss of fraction".
The reason why (which I have to smack myself now for not realizing) was that, even though I was assigning the result to a double, I was still dividing two integers. Adding a decimal point and zero to the second number of my equation, as shown below, solved the problem:
double columnCountDividedBy2 = numberOfColumns / 2.0;
double columnCountDividedBy2 = numberOfColumns / 2;
In the above example, numberOfColumns is declared as an int. I thought that, because I was assigning the result to a double, I would get a fractional number if numberOfColumns divided by 2 was not a whole number. However, what was happening was that the fraction was being dropped. ReSharper was also giving me a warning message, "possible loss of fraction".
The reason why (which I have to smack myself now for not realizing) was that, even though I was assigning the result to a double, I was still dividing two integers. Adding a decimal point and zero to the second number of my equation, as shown below, solved the problem:
double columnCountDividedBy2 = numberOfColumns / 2.0;
Comments
Post a Comment