smiley
smiley

Reputation:

Format Text from a Textbox as a Percent

I have a numeric value in a Textbox that I'd like to format as a percent. How can I do this in C# or VB.NET?

Upvotes: 4

Views: 20858

Answers (4)

DynastyOak
DynastyOak

Reputation:

A little trickery for populating Label's (& TexBox) in a panel before users input. This covers decimal, integers, percent, and strings.

Using C# 1.1 in the Page_Load event before any thing happens:

if (!this.IsPostBack)

{
    pnlIntake.Visible = true    // what our guest will see & then disappear  
    pnlResult.Visible = false   // what will show up when the 'Submit' button fires   

    txtIperson.Text = "enter who";  
    lbl1R.Text = String.Format(Convert.ToString(0));     // how many times  
    lbl2R.Text = String.Format(Convert.ToString(365));   // days a year  
    lblPercentTime = String.Format("{0:p}", 0.00);       // or one zero will work '0'  
    lblDecimal = String.Format("{0:d}", 0.00);           // to use as multiplier  
    lblMoney = String.Format("{0:c}", 0.00);             // I just like money  

    // < some code goes here - if you want
}

Upvotes: 0

Frank Krueger
Frank Krueger

Reputation: 70993

For added fun, let's make the parser a bit more sophisticated.

Instead of Double.TryParse, let's create Percent.TryParse which passes these tests:

100.0 == " 100.0 "
 55.0 == " 55%  "
100.0 == "1"
  1.0 == " 1 % "
  0.9 == " 0.9  % "
   90 == " 0.9 "
 50.0 == "50 "
1.001 == " 1.001"

I think those rules look fair if I was a user required to enter a percent. It allows you to enter decimal values along with percents (requiring the "%" end char or that the value entered is greater than 1).

public static class Percent {
    static string LOCAL_PERCENT = "%";
    static Regex PARSE_RE = new Regex(@"([\d\.,]+)\s*("+LOCAL_PERCENT+")?");
    public static bool TryParse(string str, out double ret) {
        var m = PARSE_RE.Match(str);
        if (m.Success) {
            double val;
            if (!double.TryParse(m.Groups[1].Value, out val)) {
                ret = 0.0;
                return false;
            }
            bool perc = (m.Groups[2].Value == LOCAL_PERCENT);
            perc = perc || (!perc && val > 1.0);
            ret = perc ? val : val * 100.0;
            return true;
        }
        else {
            ret = 0.0;
            return false;
        }
    }
    public static double Parse(string str) {
        double ret;
        if (!TryParse(str, out ret)) {
            throw new FormatException("Cannot parse: " + str);
        }
        return ret;
    }
    public static double ParsePercent(this string str) {
        return Parse(str);
    }
}

Of course, this is all overkill if you simply put the "%" sign outside of the TextBox.

Upvotes: 1

Joe H
Joe H

Reputation: 851

Building on Larsenal's answer, how about using the TextBox.Validating event something like this:

yourTextBox_Validating(object sender, CancelEventArgs e)
{
    double doubleValue;
    if(Double.TryParse(yourTextBox.Text, out doubleValue))
    {
        yourTextBox.Text = doubleValue.ToString("0%");
    }
    else
    {
        e.Cancel = true;
        // do some sort of error reporting
    }
}

Upvotes: 2

Larsenal
Larsenal

Reputation: 51156

In VB.NET...

YourTextbox.Text = temp.ToString("0%")

And C#...

YourTextbox.Text = temp.ToString("0%");

Upvotes: 4

Related Questions