I have SQL table with a column with a data type of Float. There is an external app that writes percentage values to this column and I read them and display them in a web app.
I understand how to convert decimal's to percentages; usually I would multiply by 100, but this is a little different.
The values in the DB look like this:
0.95 <-- DB 5% <-- UI
0.85 <-- DB 15% <-- UI
0.5 <-- DB 50% <-- UI
I have tried
number * percentage / 100
and
((percentage /100) * value).ToString();
and
string percentage = string.Format("Percentage is {0:0.0%}", value);
and
percentage/100m*value
and
myDecimal.ToString("0.00");
and finally, what I thought was close:
Math.Round(myDecimal, 2).ToString("{0.00}");
and of course various string formatting things like
MyDecimal.ToString("P"), .ToString("P1"), etc)
Articles on Formatting, Rounding and Converting Percentages in C#:
Convert percentage to nearest fraction, Working percentage in c#, http://www.dotnetperls.com/percentage,
But I can not for the life of me find a math calculation or built in c# conversion to give me the output I need.
What it seems like I need to do is get the 0.96 digits to be subtracted by some number and then in turn multiply that by 100, but the 0.5 being 50% always throws my math off....
This seems like it would be a common conversion; what I am missing here?
Here is a the solution I ended up with, which works great! (Thanks Reed)
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);
}
For the sake of completeness, here is a pretty consise list of resources on Decimals, Percentages, Doubles, and conversions in 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
I believe you'd want:
string percentage = string.Format("Percentage is {0:0.0%}", 1.0 - value);
If you just want the number:
string percentage = (1.0 - value).ToString("P");
Or, the number without decimal precision:
string percentage = (1.0 - value).ToString("P0");
Try:
(1 - currentPercentage) * 100
Example:
(1 - 0.95) * 100 = 0.05 * 100 = 5 [%]
Formatting:
string.Format("Percentage is {0}%", (1.0 - value) * 100);
Or the best one suggested by @Reed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With