Bala
Bala

Reputation: 1476

C# type conversion

dr["po_amt"].ToString() = 1,936.10;

when i try to convert this to int32 using the below code,

Convert.ToInt32(dr["po_amt"].ToString());

it throws an error input string was not in correct format. How can i achieve this

Upvotes: 0

Views: 261

Answers (4)

nitropropain
nitropropain

Reputation: 26

Try parsing to a float then converting to Int32:

var d = float.Parse("1936,10");
Convert.ToInt32(d);

Upvotes: 0

Martin Liversage
Martin Liversage

Reputation: 106926

You cannot convert 1,936.10 to an integer, but you can convert it to a floating point and then cast it:

(Int32) Convert.ToDouble("1,936.10", CultureInfo.InvariantCulture)

Note the use of the CultureInfo to avoid problems when you run in a locale where the floating point number format is different.

Casting the floating point number will truncate the fractional part. If you need to round it you should apply the Math.Round() before casting it.

Upvotes: 3

Peter Perháč
Peter Perháč

Reputation: 20792

Convert it to Double and cast it to int

int i = (int)Convert.ToDouble("1203.12");

works :-)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503519

You're trying to convert "1,936.10" into an integer. That's clearly not an integer. You should parse it as a floating point number (e.g. with decimal.TryParse) and then apply whatever conversion you want to get an integer afterwards, if indeed you really do want an integer.

(I would strongly advise you to use decimal.TryParse over float.TryParse or double.TryParse, by the way. Obviously the string is representing a number in decimal, so that's the most appropriate type to use.)

When converting to decimal, you should specify the invariant culture (in case you're in a region which uses "." for the thousands separator and "," as the decimal separator), and it wouldn't hurt to explicitly specify the number style, allowing thousands.

Upvotes: 9

Related Questions