C# 如何格式化带有数字输入的千位分隔符和小数分隔符的 Windows 窗体文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15473216/
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
how to format a windows forms Textbox with thousand separator and decimal separtor for Numeric input
提问by ethem
I'm newbie with Winforms and try to do something. I'm using C#. I'm using windows forms and I've put a 8 textbox on my form, 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.... Can someone advice how to achieve the below approach?
我是 Winforms 的新手,并尝试做一些事情。我正在使用 C#。我正在使用 Windows 窗体,并且在窗体上放置了一个 8 文本框,所有文本框都是带十进制值的数字。我喜欢实现以下结果。我的小数点分隔符是一个逗号,千位分隔符是一个点。我曾经见过像##.###、## 或其他类似的东西,但不记得了……有人可以建议如何实现以下方法吗?
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.
所以这个想法是,当我输入 1234 并将焦点从文本框中离开时,它应该格式化,当我再次进入文本框时,千位分隔符不应只格式化小数点分隔符。
I think I've to use some events like LostFocus?
我想我必须使用一些事件,比如 LostFocus?
input result
输入结果
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
采纳答案by Fendy
On your LostFocus event in textbox, use:
在文本框中的 LostFocus 事件中,使用:
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 exception. This solution is rather harsh, tough.
在应用上述逻辑之前,请先确保文本是双精度/整数,否则会抛出异常。这个解决方案相当苛刻、艰难。
If you want the format to be in 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 Indonesian currency format, which thousand separator use dot (".") rather than comma (",").
上面的例子是印度尼西亚货币格式,千位分隔符使用点(“.”)而不是逗号(“,”)。
回答by stevepkr84
Perhaps you could use the MaskedTextBox
也许你可以使用 MaskedTextBox
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
You could adjust the mask based on the input length when losing focus. Hope this is helpful.
您可以在失去焦点时根据输入长度调整蒙版。希望这是有帮助的。