Search code examples
c#typesulong

Why does this ulong divided by ulong give me 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.


Solution

  • 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;