Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousand separated value to integer

Tags:

c#

I want to convert a thousand separated value to integer but am getting one exception.

double d = Convert.ToDouble("100,100,100"); 

is working fine and getting d=100100100

int n = Convert.ToInt32("100,100,100");

is getting one format exception

Input string was not in a correct format

Why?

like image 566
niknowj Avatar asked May 26 '11 13:05

niknowj


People also ask

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.

How can I parse a string with a comma thousand separator to a number?

To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.


2 Answers

try this:

int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);

Note that the Parse method will throw an exception on an invalid string, so you might also want to check out the TryParse method as well:

string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
    // if you are here, you were able to parse the string 
}
like image 114
matt Avatar answered Oct 23 '22 11:10

matt


What Convert.ToInt32 is actually calling in your example is Int32.Parse.

The Int32.parse(string) method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).

Since your's contained commas, it threw an exception.

like image 28
kemiller2002 Avatar answered Oct 23 '22 12:10

kemiller2002