2

I have a very silly problem .. I have a string containing "800.0000" (without the quotes), which I'm trying to convert to the number 800. I'm using this command, but its not working:

int inputNumber = Int32.Parse(inputString);

I get the FormatException, with the message "Input string was not in a correct format."

6 Answers 6

11

Try this:

int inputNumber = Int32.Parse(inputString, NumberStyles.AllowDecimalPoint);
Sign up to request clarification or add additional context in comments.

Comments

3

800.000

is of type Double, not an Integer

so,

double inputNumber = Double.Parse(inputString);

Will work for you.

Comments

1

The Exception occurs because your string is no int32. You have to convert to double first.

double value = Convert.ToDouble(youString);

Comments

1

Try this:

double myDouble = Convert.ToDouble(string);

works similarly with other types too,

int myInt = Convert.ToInteger(string);

Comments

1

Since you are passing a number that's got decimals, you'll need to use the appropriate target type - float or double

So that gives you

var value = Double.Parse(s);

You can take away the decimals like this:

var integer = (int)value;

But even with the Double.Parse you'll need to be careful, since it will expect different input based on the current culture (System.Globalization.CultureInfo.CurrentCulture).

So while

Double.Parse("800.00", System.Globalization.CultureInfo.GetCultureInfo("en-US"))

works as expected

Double.Parse("800.00", System.Globalization.CultureInfo.GetCultureInfo("de-DE"))

will produce the value "80000"

EDIT1 - added:

So you'll might want to use

Double.Parse("800.00", System.Globalization.CultureInfo.InvariantCulture)

to prevent any misinterpretation that can lead to all kinds of trouble.

Comments

0

Int32 valueInInt = (int)double.Parse(inputString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.