Convert.ToInt32()用逗号的字符串 [英] Convert.ToInt32() a string with Commas
问题描述
我有,有时有逗号分隔条件如 1500
数字符串,我需要将其转换为int,目前它抛出一个异常,可有人告诉我如何解决这个问题,这样有时我会用逗号等次了逗号输入数字,它仍然会进行转换。
I have a string that sometimes has commas seperating the number like 1,500
and I need to convert this to an Int, currently it is throwing an exception, can someone tell me how to fix this so that sometimes I may input numbers with commas and other times with out commas and it will still convert.
推荐答案
您可以使用 int.Parse
并添加<一个href=\"http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx\"><$c$c>NumberStyles.AllowThousands$c$c>标志:
You could use int.Parse
and add the NumberStyles.AllowThousands
flag:
int num = int.Parse(toParse, NumberStyles.AllowThousands);
或<一个href=\"http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx\"><$c$c>int.TryParse$c$c>让你知道,如果操作成功:
Or int.TryParse
letting you know if the operation succeeded:
int num;
if (int.TryParse(toParse, NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out num))
{
// parse successful, use 'num'
}
这篇关于Convert.ToInt32()用逗号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!