Problem to show the number's decimal?

ken76

Member
Joined
Nov 15, 2018
Messages
7
Programming Experience
5-10
I have problem with the code below this text. It doesn't show any decimals, only the number 0. Can someone help me to correct this code, so it shows also the decimals. In this case it enough with 2 decimals.

double answerCount;
answerCount = 5 / 20;
answerCount = Math.Round((Double)answerCount, 2);
 

Skydiver

Well-known member
Joined
Apr 6, 2019
Messages
922
Location
Virginia Beach, VA
Programming Experience
10+
The reason is because you are doing integer division, not floating point division, here:
Code:
answerCount = 5 / 20;
5 whole objects cannot be divided into 20 whole objects so the result is 0. 0 to two decimal places is 0.00.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
2,616
Location
Sydney, Australia
Programming Experience
10+
As suggested, an int divided by an int always results in an int. If you want a double result then at least one of the operands must be a double. If you read the documentation for the division operators for the two types you'll see that.
 

Sheepings

Senior Programmer
Joined
Sep 5, 2018
Messages
844
Location
UK
Programming Experience
10+
I think someone needs to get there tables book out and skip towards the last few pages after the division section. ;)
 
Top Bottom