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;

Comments

I would like to ask you to recommend other sources dedicated to this theme in case you happen to know any of them.

Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception