将文本框中的文本格式设置为百分比

时间:2022-06-08 21:12:17

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?

我在文本框中有一个数字值,我想格式化为百分比。如何在C#或VB.NET中执行此操作?

4 个解决方案

#1


In VB.NET...

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

And C#...

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

#2


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

基于Larsenal的回答,如何使用TextBox.Validating事件如下:

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
    }
}

#3


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:

而不是Double.TryParse,让我们创建通过这些测试的Percent.TryParse:

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).

如果我是一个需要输入百分比的用户,我认为这些规则看起来很公平。它允许您输入十进制值和百分数(需要“%”结束字符或输入的值大于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.

当然,如果您只是将“%”符号放在TextBox之外,这就太过分了。

#4


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

在用户输入之前在面板中填充Label(&TexBox)的小技巧。这包括十进制,整数,百分比和字符串。

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

在任何事情发生之前在Page_Load事件中使用C#1.1:

if (!this.IsPostBack)

{

pnlIntake.Vissible=true'    // what our guest will see & then disappear  
pnlResult.Vissible=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 >
}

#1


In VB.NET...

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

And C#...

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

#2


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

基于Larsenal的回答,如何使用TextBox.Validating事件如下:

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
    }
}

#3


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:

而不是Double.TryParse,让我们创建通过这些测试的Percent.TryParse:

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).

如果我是一个需要输入百分比的用户,我认为这些规则看起来很公平。它允许您输入十进制值和百分数(需要“%”结束字符或输入的值大于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.

当然,如果您只是将“%”符号放在TextBox之外,这就太过分了。

#4


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

在用户输入之前在面板中填充Label(&TexBox)的小技巧。这包括十进制,整数,百分比和字符串。

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

在任何事情发生之前在Page_Load事件中使用C#1.1:

if (!this.IsPostBack)

{

pnlIntake.Vissible=true'    // what our guest will see & then disappear  
pnlResult.Vissible=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 >
}