-1

Let's assume I have 8 items.

From these 8, 5 are success and 3 failure.

If I want to get the success and failure in percentage with 2 decimals precission I will do like this:

int total = 8;
int success = 5;
int failure = 3;

string success =((decimal)((success * 100) / total)).FormatDecimal();

string failure = ((decimal)((failure * 100) / total)).FormatDecimal();

Format decimal is an extension that will convert decimal to string with x amount of decimals.

public static string FormatDecimal(this decimal value, int decimals = 2)
{
   return value.ToString(string.Format("0.{0}", new string('0', decimals)));
}

Now if I take my calculator and I do this, the result is correct:

success: (5 * 100) / 8 = 62.5 %

failure: (3 * 100) / 8 = 37.5 %

However my solution return me 62.00 % and 37.00%

What's wrong with my code?

Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
user2818430
  • 5,853
  • 21
  • 82
  • 148

3 Answers3

1

Because your code is running with integer division but you calculator can do floating-point division.

Your (5 * 100) / 8 returns 62, not 62.5 since both operand is int and this operation will always disregards fractional part.

From / Operator (C# Reference)

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.

If you change your total to double, you can fix this since you start doing floating-point division not integer division.

double total = 8.0;

Check out;

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

That's because the division operator / for integers only return the integer part.

If need to cast to float, double or decimal.

var result = ((float)(5 * 100)) / 8;

If any of the values you are dividing is a float, double or decimal, the division operator will support the decimal part.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
0

This is very basic mistake at C#. You have defined the calculation wrong.

(success * 100) / total

It means that after success * 100, the result will be parsed as integer. It is now 300 in integer. 300 / 8 = 37 in integer.

Instead, you can replace the 100 with 100m to force convert them to decimal.

Fendy
  • 4,565
  • 1
  • 20
  • 25