Link to home
Start Free TrialLog in
Avatar of amoran
amoran

asked on

Rounding?

Hi
if uptime and downtime are ints and uptime = 2 and downtime = 1
How would I displayed it as a percentage (as Im trying to do)

I want it to say 66.66% and 33.33%

Thanks

decimal percentageworth;
            if ((uptime + downtime) != 0)
                percentageworth = 100 / (uptime + downtime);
            else
                percentageworth = 1;

            label1.Text = "Uptime is " + this.uptime.ToString() + "(" + Math.Round(uptime * percentageworth, 2) + "%)";
            label2.Text = "Downtime is " + this.downtime.ToString() + "(" + Math.Round(downtime * percentageworth, 2) + "%)";
           
Avatar of neilprice
neilprice

Hi,

Try

double percentUptime = (double)(uptime)/(double)(uptime + downtime);
double percentDowntime = (double)(downtime)/(double)(uptime + downtime);

Hope this helps,
Neil
ASKER CERTIFIED SOLUTION
Avatar of neilprice
neilprice

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of amoran

ASKER

Neil,
That gave me
NaN
and
0.33333333333333333333%
?!
Avatar of amoran

ASKER

Ok

This works

label1.Text = "Uptime is " + this.uptime.ToString() + "/" + (uptime + downtime).ToString() + " (" + Math.Round(((double)(uptime) / (double)(uptime + downtime)) * 100, 2).ToString() + "%)";
            label2.Text = "Downtime is " + this.downtime.ToString() + "/" + (uptime + downtime).ToString() + "(" + Math.Round(((double)(downtime) / (double)(uptime + downtime)) * 100, 2).ToString() + "%)";
           

just not sure what NaN means.
Or you could try...

 string percentUptime;
            string percentDowntime;

            if(uptime!=0)
            {
                percentUptime = (((double)(uptime) / (double)(uptime + downtime)) * 100).ToString();
                if (percentUptime.Length > 5)
                    percentUptime = percentUptime.Substring(0, 5);
            }
            else
            {
                percentUptime="0";
            }
            if(downtime!=0)
            {
                percentDowntime = (((double)(downtime) / (double)(uptime + downtime)) * 100).ToString();
                if (percentDowntime.Length > 5)
                    percentDowntime = percentDowntime.Substring(0, 5);
            }
            else
            {
                percentDowntime = "0";
            }
            percentUptime += "%";
            percentDowntime += "%";

Which will check for divide by 0 errors and format the string to just two decimal places as you want.

Neil
NaN generally means Not a Number - you can get it dividing 0 by 0.

see: http://msdn2.microsoft.com/en-us/library/system.double.nan.aspx

Neil