【发布时间】:2013-01-20 20:36:02
【问题描述】:
我有一个 SQL 表,其中有一列的数据类型为 Float。有一个外部应用程序将百分比值写入此列,我读取它们并将它们显示在 Web 应用程序中。
我了解如何将小数转换为百分比;通常我会乘以 100,但这有点不同。
数据库中的值如下所示:
0.95 <-- DB 5% <-- UI
0.85 <-- DB 15% <-- UI
0.5 <-- DB 50% <-- UI
我试过了
number * percentage / 100
和
((percentage /100) * value).ToString();
和
string percentage = string.Format("Percentage is {0:0.0%}", value);
和
percentage/100m*value
和
myDecimal.ToString("0.00");
最后,我认为很接近:
Math.Round(myDecimal, 2).ToString("{0.00}");
当然还有各种字符串格式化的东西,比如
MyDecimal.ToString("P"), .ToString("P1"), etc)
关于在 C# 中格式化、舍入和转换百分比的文章:
Convert percentage to nearest fraction, Working percentage in c#, http://www.dotnetperls.com/percentage,
但我无法终生找到数学计算或内置 c# 转换来给我所需的输出。
似乎我需要做的是让 0.96 位数字减去某个数字,然后再乘以 100,但 0.5 是 50% 总是让我的数学题无法计算......
这似乎是一种常见的转换;我在这里缺少什么?
更新
这是我最终得到的解决方案,效果很好! (感谢里德)
var li = new List<Object>();
var retVal = new List<string>();
li.Add(.5); // 50%
li.Add(.95); // 95%
li.Add(.85); // 85%
li.Add(0.87813); // 12.18700%
foreach (var o in li)
{
var value = Convert.ToDouble(o);
string percentage = string.Format("Percentage is {0:0.0%}", 1.0 - value);
retVal.Add(percentage);
}
链接
为了完整起见,这里有一个关于小数、百分比、双精度和 C# 转换的非常简洁的资源列表:
A+
Working percentage in c#
Format decimal for percentage values?
Convert percentage to nearest fraction
http://www.dotnetperls.com/percentage
.NET: Decimal to rounded string
C# Is there a built-in function to convert a formatted String back to a Number?
A-
Format decimal as a percent with specific decimal places
Convert decimal to percent or shift decimal places. How
How to convert percentage string to double?
B+
two ways of displaying a decimal
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
【问题讨论】:
-
1 - 0.95 = 0.05然后0.05 * 100 = 5然后格式化为字符串并将%放在末尾span>
标签: c# type-conversion decimal percentage