Convert.ToInt32()用逗号的字符串 [英] Convert.ToInt32() a string with Commas

查看:207
本文介绍了Convert.ToInt32()用逗号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,有时有逗号分隔条件如 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标志:

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让你知道,如果操作成功:

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屋!

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