我有一个字符串,有时用逗号分隔数字,例如1,500
我需要将其转换为 Int,目前它抛出异常,有人可以告诉我如何解决这个问题,以便有时我可以输入带逗号的数字,有时不带逗号,它仍然会转换。
你可以使用int.Parse http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx并添加NumberStyles.AllowThousands http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx flag:
int num = int.Parse(toParse, NumberStyles.AllowThousands);
Or int.TryParse http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx让您知道操作是否成功:
int num;
if (int.TryParse(toParse, NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out num))
{
// parse successful, use 'num'
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)