Skip to main content
 首页 » 编程设计

c#之如何将数字四舍五入并显示为百分比

2024年02月23日16leader

我的数学有点生疏,所以我希望有人能帮助我。使用下面的代码,我想执行以下操作:根据安装的内存量,我想显示可用内存的百分比,而不是剩余的内存量(以兆字节为单位)。

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

请您参考如下方法:

(可用内存/总内存)* 100 将是您的百分比。

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