C# 将文本框中的文本格式化为百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/849799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:07:30  来源:igfitidea点击:

Format Text from a Textbox as a Percent

c#.netvb.netformatting

提问by

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

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

采纳答案by Larsenal

In VB.NET...

在 VB.NET 中...

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

And C#...

和 C#...

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

回答by Joe H

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

回答by Frank Krueger

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

为了增加乐趣,让我们让解析器更复杂一点。

Instead of Double.TryParse, let's create Percent.TryParsewhich 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 outsideof the TextBox.

当然,这是如果你简单地把“%”符号所有矫枉过正之外TextBox

回答by Frank Krueger

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

在用户输入之前在面板中填充标签(和 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 >
}