简体   繁体   English

C#格式到千位分隔符

[英]C# format to thousand seperator

I am trying to format user input to a thousand seperator format. 我正在尝试将用户输入格式化为千位分隔符格式。 I tried the code here, but it keeps breaking the application: 我在这里尝试了代码,但它不断破坏应用程序:

Amt.Text = String.Format("{0:0,0.00}", Convert.ToDouble(Amt));

So when the user inputs 3566412 , then it needs to convert automatically to 3,566,412 因此,当用户输入3566412 ,它需要自动转换为3,566,412

You are trying to convert the control (named Amt ) to a double , which is a bad idea since you want to convert the text of the control ( Amt.Text ). 您试图将控件(名为Amt )转换为double ,这是个坏主意,因为您要转换控件的文本( Amt.Text )。 I would suggest to use a decimal since that is more precise and will not cause floating point issues: 我建议使用decimal因为这样更精确,并且不会引起浮点问题:

Amt.Text = String.Format("{0:0,0.00}", Convert.ToDecimal(Amt.Text));

Another thing to consider is to use a control that can mask itself, so you don't need to replace the text yourself every time. 要考虑的另一件事是使用可以掩盖自身的控件,因此您不必每次都自己替换文本。

You might want to check out Standard Numeric Format Strings at MSDN 您可能想在MSDN上签出标准数字格式字符串

Then you could do something like 然后你可以做类似的事情

Amt.Text = inputnumber.ToString("N");

Which will format 3566412 to 3,566,412.0 这会将3566412格式化为3,566,412.0

If you want to take it directly from the textbox, you could do something like this, which checks if the text can be parsed before setting the text 如果您想直接从文本框中获取它,则可以执行类似的操作,该检查在设置文本之前检查是否可以解析文本

double result = 0;
if (double.TryParse(Amt.Text, out result)
{
    Amt.Text = result.ToString("N");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM