2011-09-21 46 views
1

我對數學有些生疏,所以我希望有人能幫助我。使用下面的代碼我想要做到以下幾點:根據安裝的內存量,我想顯示可用內存的百分比,而不是剩下多少兆字節。如何四捨五入數字並以百分比顯示?

private void timer1_Tick(object sender, EventArgs e) 
{ 
    string memory; 
    int mem; 
    memory = GetTotalMemoryInBytes().ToString(); 
    mem = Convert.ToInt32(memory); 
    mem = mem/1048576; 
    progressBar2.Maximum = mem; 
    progressBar2.Value = mem - (int)(performanceCounter2.NextValue()); 
    label2.Text = "Available Memory: " + (int)(performanceCounter2.NextValue()) + "Mb"; 


} 

//using Microsoft visual dll reference in c# 
static ulong GetTotalMemoryInBytes() 
{ 
    return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; 
} 
+1

任何特定的原因你獲取總內存,將其轉換爲字符串,然後將字符串轉換回數字? –

+0

嗨馬克...我是C#的新手,因此我的技能不好:) –

回答

2

(Available memory/Total memory) * 100將是你的百分比。

double percent = ((performanceCounter2.NextValue() * 1.0)/mem) * 100; 
label2.Text = "Available Memory: " + percent; 
+0

嗨rohit89 ...感謝您對代碼的解釋!完美工作。我如何四捨五入以便在小數點後不顯示任何內容?謝謝 –

+0

'Math.Ceiling(百分比)'會湊整。 – rohit89

0

mem/memory將是已使用內存的百分比。爲了獲得可用的內存百分比,其1減去結果。但可能需要一個double

2

爲了得到一個百分比,可以使用:part/total * 100,如:

var Info = Microsoft.VisualBasic.Devices.ComputerInfo(); 

var PercentAvailable = Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory * 100; 
var PercentLeft = 100 - PercentAvailable; 

// or alternatively: 
var PercentLeft = (1 - Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory) * 100; 
0

對於大多數新機器而言,總內存容量至少爲2GB。這不適合Int32,所以你不會工作。既然你想要四捨五入,你應該使用Math.Ceiling。

ulong total = My.Computer.Info.TotalPhysicalMemory; 
ulong available = My.Computer.Info.AvailablePhysicalMemory; 
int pctAvailable = (int)Math.Ceiling((double)available * 100/total); 
int pctUsed = (int)Math.Ceiling((double)(total - available) * 100/total);