用户键入时:用逗号分隔数字,并将其格式化为C#货币 [英] As the user types: Separate numbers with commas, and format it into currency in C#

查看:123
本文介绍了用户键入时:用逗号分隔数字,并将其格式化为C#货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为textBox1的文本框。

I have a textbox called textBox1.

目标:用户键入textBox1后,我希望程序将数字转换为货币格式。

Goal: As soon as the user types in textBox1, I want the program to convert the numbers into currency format.

示例:如果用户键入123456,我希望程序像这样分隔数字123,456。

Example: If the user typed 123456, I want the program to separate the numbers 123,456 like so.

推荐答案

根据研究,我遇到了此代码。这段代码正是我想要的。

Upon research I came across this code. This code did exactly what i wanted.

    private void form_3_Load(object sender, EventArgs e)
    {
        textBox1.Text = "$0.00";
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        ///
        //Remove previous formatting, or the decimal check will fail including leading zeros
        string value = textBox1.Text.Replace(",", "")
            .Replace("$", "").Replace(".", "").TrimStart('0');
        decimal ul;
        //Check we are indeed handling a number
        if (decimal.TryParse(value, out ul))
        {
            ul /= 100;
            //Unsub the event so we don't enter a loop
            textBox1.TextChanged -= textBox1_TextChanged;
            //Format the text as currency
            textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
            textBox1.TextChanged += textBox1_TextChanged;
            textBox1.Select(textBox1.Text.Length, 0);
        }
        bool goodToGo = TextisValid(textBox1.Text);
        btn_test.Enabled = goodToGo;
        if (!goodToGo)
        {
            textBox1.Text = "$0.00";
            textBox1.Select(textBox1.Text.Length, 0);
        }
        ///
    }

    private bool TextisValid(string text)
    {
        Regex money = new Regex(@"^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$");
        return money.IsMatch(text);
    }


    void tb_TextChanged(object sender, EventArgs e)
    {
        //Remove previous formatting, or the decimal check will fail
        string value = textBox1.Text.Replace(",", "").Replace("$", "");
        decimal ul;
        //Check we are indeed handling a number
        if (decimal.TryParse(value, out ul))
        {
            //Unsub the event so we don't enter a loop
            textBox1.TextChanged -= tb_TextChanged;
            //Format the text as currency
            textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
            textBox1.TextChanged += tb_TextChanged;
        }
    }

这篇关于用户键入时:用逗号分隔数字,并将其格式化为C#货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆