Reputation: 207
I am getting data into a text field and I need to display it as a percentage. Is there a function to perform this?
Ex: in my column I have "0.5", "0.1","0.2","0.25"
etc., which needs to be displayed as
50%,10%,20%,25%
etc., What is the best way to do it?
Upvotes: 3
Views: 5302
Reputation:
Easiest would be to parse it (must be a double) then convert it back to a string, formatting it as a percentage.
var percentageString = double.Parse(doubleString).ToString("p1");
Now, some of you hoity-toity types may say that decimal is the correct type to use in this case.
Well, yes, if you need an additional 12-13 digits of precision.
However, most of us real folk (and I'm all about keeping it real) are fine with double's 15-16 digits of precision.
The real choice is whether or not your code is using doubles or decimals in the first place. If you are using doubles in your code, just stick with doubles. If decimals, stick to decimals. What you definitely do want to avoid is having to convert between the two any more than is absolutely necessary, as there be dragons. And unexpected runtime bugs that can corrupt your data. But mostly dragons.
Upvotes: 4
Reputation: 1500735
You should do this in two phases:
So:
decimal percentage = decimal.Parse(input);
string output = percentage.ToString("p0");
Notes:
decimal
rather than double
to exactly represent the value in the text (for example, the text could have "0.1" but double
can't hold a value of exactly 0.1)Upvotes: 11