4

I am trying to calculate percentage of the given long value. The following code is returning zero . How to calculate percentage in c#

long value = (fsize / tsize) * (long)100;

Here fsize and tsize is some Long values.

  • 5
    what are the values of fsize and tsize? what types are they? when you set breakpoints and debug, what happens? – user1666620 Jul 14 '15 at 15:04
  • 1
    I believe all your operands are int/long type and you are doing integer arithmetic. – Habib Jul 14 '15 at 15:05
  • Are `fsize` and `tsize` integers, then this is an integer divison which results also in an int-value. – Tim Schmelter Jul 14 '15 at 15:05
  • 2
    Not a very good duplicate target. The problem is more about data types and not actually about how to calculate a percentage. – ryanyuyu Jul 14 '15 at 15:06

3 Answers3

7

Try this

var value = ((double)fsize / tsize) * 100;
var percentage = Convert.ToInt32(Math.Round(value, 0));
NASSER
  • 5,900
  • 7
  • 38
  • 57
3

You could try something like this:

double value = ((double)fsize / (double)tsize) * 100.0;

if fsize is int and tsize is int then the division is also an int and 0 is the correct answer. You need to convert it to double to get the correct value back.

radu florescu
  • 4,315
  • 10
  • 60
  • 92
2

best way to do this

int percentage = (int)Math.Round(((double)current / (double)total) * 100);
Harry007
  • 47
  • 1
  • 7