0

I am grabbing total RAM of a computer system and available RAM and trying to work out what percentage is available.

I am using the following code:

double percent = my.Info.AvailablePhysicalMemory / my.Info.TotalPhysicalMemory;

and have also tried:

decimal percent = my.Info.AvailablePhysicalMemory / my.Info.TotalPhysicalMemory;

I am sure it's an issue with the type but I am unsure why both methods give a result of 0.

The actual values are Total: 17072574464 and Available: 8746000384. The values come back from the system cast as ulong. So what does percent always equal 0? If I put the numbers in directly it works fine. Just can't use the ulong variables - hence why I am sure it's my lack of experience with types in C# that is the problem.

SystemX17
  • 3,637
  • 4
  • 25
  • 36
  • 3
    Integer math. Convert one or both operands to double (or decimal, depending on which line you've kept) before or while dividing. – Anthony Pegram Apr 10 '19 at 17:45
  • 1
    Nothing to do with ulong: `10 / 11 = 0` – TaW Apr 10 '19 at 17:47
  • @TaW 10 / 11 != 0 on a calculator. It was that I was working with ulong (integer) values as they were incorrectly cast for what I was trying to do. Thanks everyone for the help. – SystemX17 Apr 10 '19 at 17:57
  • 1
    Indeed c# is not a calculator but a language. You have to understand the rules and it will reward you by doing ~anything you want.. – TaW Apr 10 '19 at 18:05
  • 2
    I *really* wish the C# compiler warned about this. "Late conversion" is a common error amongst both novice and experienced programmers. You also see it in multiplication, where we have `long r = a * b;` where `a` and `b` are integers big enough to overflow into a long when multiplied, but that's not what happens. – Eric Lippert Apr 10 '19 at 18:22
  • 1
    If the subject of how people get integer division wrong interests you, there are some good examples here: https://stackoverflow.com/questions/921180/how-can-i-ensure-that-a-division-of-integers-is-always-rounded-up/926806#926806 – Eric Lippert Apr 10 '19 at 20:27

1 Answers1

1

You are trying to divide an integer by an integer, which always rounds down. You need to convert to a floating point number before you divide; for example:

double percent = my.Info.AvailablePhysicalMemory * 1.0 / my.Info.TotalPhysicalMemory;
fluffy
  • 5,212
  • 2
  • 37
  • 67
  • 2
    `double(my.Info.AvailablePhysicalMemory)` doesn't compile, did you mean `(double)my.Info.AvailablePhysicalMemory`? – Camilo Terevinto Apr 10 '19 at 17:52
  • 1
    You can also write `1.0 * my.Info.AvailablePhysicalMemory / my.Info.TotalPhysicalMemory;` – TaW Apr 10 '19 at 18:05
  • Thanks, I brainfarted on how C# casting looks. I'd originally used `1.0` but switched to an explicit cast because I figured someone would peg it as bad style. :P (Also @SystemX17 I'm not a 'he') – fluffy Apr 10 '19 at 18:16
  • 1
    Have removed the gendered comment fluffy. My apologies. – SystemX17 Apr 10 '19 at 18:31