1

Alright, so I'm trying to get the percentage of uppercase letters in a string. However, I'm not having much luck as my current code only says prints out if 100% of the string is uppercase.

int capsCount = 0;
foreach (char c in e.message)
{
    if (Char.IsUpper(c))
        capsCount++;
}

Console.WriteLine($"{(capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%")} is caps.");
Console.WriteLine($"{e.message.Replace(" ", string.Empty).Length}:{capsCount}");

Output from the console, #sydth is the irc channel, sydth is the username, and test is the message.

#sydth:sydth:TEST
100.00% is caps.
4:4

#sydth:sydth:test
0.00% is caps.
4:0

#sydth:sydth:teST
0.00% is caps.
4:2
Sydth
  • 23
  • 2
  • 2
    My guess is the reason is because Length() and capsCount are both integers, so the result of division is integer as well. Convert them to floats before division. – Bart Feb 24 '16 at 08:48

2 Answers2

1

You need to cast at least one of the properties in the division of the capsCount and the number of characters in the string to a decimal so it treats the division as decimal division rather than an integer division.

Console.WriteLine($"{((decimal)capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%")} is caps.");

Or you could make capsCount a decimal rather than an int;

decimal capsCount = 0;
foreach (char c in e.message)
{
    if (Char.IsUpper(c))
        capsCount++;
}

Console.WriteLine($"{(capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%")} is caps.");
Console.WriteLine($"{e.message.Replace(" ", string.Empty).Length}:{capsCount}");
Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19
0

This is because your capsCount is int and never casted to double/float/decimal. And note that you divide it by string.Length which is also an int.

capsCount/e.message.Replace(" ", string.Empty).Length //both are int

Thus when you divide lower valued integer with higher value integer:

(int)9/(int)20 //illustration 9/20 -> 0.45 -> rounded down to 0

the result is rounded down and you will always get zero (and e.message.Length is always greater than capsCount)

The easiest solution would be to define it as double in the first place.

double capsCount; //declare as double

Alternatively, simply cast it double first before operation:

((double)capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%") //note that there is (double) there for casting
Ian
  • 30,182
  • 19
  • 69
  • 107