百分比计算
我正在 ASP.NET MVC 2 中研究进度条概念。这里我有一个 DropDownList,它有 10 个值。我想计算进度条的百分比,例如 DropDownList 中的 10 个值,并且我有一个返回值 2 的查询。因此,在 10 个值中我得到 2。应该显示“20 % 已完成”。如何做这个计算
I am working in progress bar concept in ASP.NET MVC 2. Here i have a DropDownList which has 10 values. i want to calculate the percentage for progress bar, e.g. 10 values from DropDownList and i am having a query which returns the value 2. so, out of 10 values i am getting 2. "20 % completed" should be displayed.. How to do this calculation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用
Math.Round()
:或手动舍入:
Using
Math.Round()
:or manually rounding:
(当前/最大值)* 100
。在您的情况下,(2 / 10) * 100
。(current / maximum) * 100
. In your case,(2 / 10) * 100
.使用 C# 字符串格式,您可以避免乘以 100,因为它会使代码更短、更清晰,特别是因为括号更少,而且还可以避免向上舍入代码。
// 输出 - 16.67%
With C# String formatting you can avoid the multiplication by 100 as it will make the code shorter and cleaner especially because of less brackets and also the rounding up code can be avoided.
// Output - 16.67%
从数学上讲,从两个数字获取百分比:
并且从百分比计算:
Mathematically, to get percentage from two numbers:
And also, to calculate from a percentage :
您可以将百分比保留为十进制
(值\总计)
,然后当您想要渲染给人类时,您可以使用Habeeb 的答案或使用字符串插值 你可以有更干净的东西:或
You can hold onto the percentage as decimal
(value \ total)
and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:or
请记住,如果您有两个整数,您可能需要将其中一个数字转换为双倍
Bear in mind that you may need to cast one of the numbers to double if you have two ints
就我而言,我设置了两个整数,并尝试计算百分比,但总是得到 0;
我的代码(之前)
在研究之后(之后)
In my case, I set two ints, and trying to calculate the percentage, and always get 0;
my code (before)
after doing research (after)
//对于其他人
如果需要使用负数计算:
//For other people
If you need calculate using negative numbers: