svs
svs

Reputation: 207

Convert text data into percentage in C#

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

Answers (2)

user1228
user1228

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

Jon Skeet
Jon Skeet

Reputation: 1500735

You should do this in two phases:

  • Parse the text as a number so you've got the value as your "real" type. (As a general rule, parse from text as early as you can, and format to a string as late as you can... operations between the two will be a lot simpler using the natural type.)
  • Format the number as a percentage using the standard numeric format string for percentage

So:

decimal percentage = decimal.Parse(input);
string output = percentage.ToString("p0");

Notes:

  • You should consider both input and output culture; are you always expecting to use "." as the decimal separator, for example?
  • Use 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)
  • You can add things like desired precision to the formatting; see the linked docs for details; the example gives just an integer percentage, for example

Upvotes: 11

Related Questions