如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入 [英] How to format a Windows Forms Textbox with thousand separator and decimal separtor for numeric input

查看:15
本文介绍了如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Windows 窗体的新手并尝试做一些事情.我正在使用 C#.

I'm new to Windows Forms and try to do something. I'm using C#.

我使用的是 Windows 窗体,我在窗体上放置了八个文本框,并且都是带有十进制值的数字.

I'm using Windows Forms and I've put eight textboxes on my form, and all are numeric with decimal value.

我喜欢实现以下结果.我的小数分隔符是逗号,千位分隔符是点.我见过像##.###,## 之类的东西,但不记得了....我怎样才能实现以下方法?

I like to achieve the results below. My decimal separator is a comma and thousand separator is a dot. I've ever seen something like ##.###,## or whatever, but don't remember.... How can i achieve the below approach?

所以我的想法是,当我输入 1234 并将焦点从文本框中移开时,它应该格式化,当我再次回到文本框时,千位分隔符不应该只格式化小数分隔符.

So the idea is when I type 1234 and leave the focus from the textbox it should format and when I get in the textbox back again the thousand separator should not format only the decimal separator.

我想我必须使用一些事件,比如 LostFocus.

I think I've to use some events like LostFocus.

输入 结果

1234 1.234,00

1234                1.234,00

12.34 12,34

12.34                    12,34

12,34 12,34

12,34                    12,34

1234567 1.234.567,00

1234567     1.234.567,00

12,34 12,34

12,34                    12,34

12345,67 12.345,67

12345,67     12.345,67

推荐答案

在文本框中的 LostFocus 事件中,使用:

On your LostFocus event in the textbox, use:

textBox1.Text = string.Format("{0:#,##0.00}", double.Parse(textBox1.Text));

在应用上述逻辑之前,请先确保文本是双精度/整数,否则会引发异常.这个解决方案相当苛刻、强硬.

Make sure that the text is double / integer first before applying the above logic or it will throw an exception. This solution is rather harsh, tough.

如果您希望格式采用特定文化而不是您当前计算机的文化,那么

If you want the format to be in a specific culture rather than your current computer's culture, then

textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));

以上示例适用于印度尼西亚货币格式,其中千位分隔符使用点(.")而不是逗号(,").

The above example is for the Indonesian currency format, in which the thousand separator use dot (".") rather than comma (",").

这篇关于如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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