Reputation: 343
I have a simple code in c# that converts a string into int
int i = Convert.ToInt32(aTestRecord.aMecProp);
aTestRecord.aMecProp
is of string
. The test I am running, during that it has values of 1.15
in string
.
but above line throws error saying that input string wasn't in a format!
I don't understand why?
I am using VS 2008 c#
Upvotes: 0
Views: 1944
Reputation: 41
ok I think this is
float d = Convert.ToSingle(aTestRecord.aMecProp);
Upvotes: 0
Reputation: 2329
Do you need a C# equivalent for the JavaScript parseInt function? I have used this one on occasion:
public int? ParseInt(string value)
{
// Match any digits at the beginning of the string with an optional
// character for the sign value.
var match = Regex.Match(value, @"^-?\d+");
if(match.Success)
return Convert.ToInt32(match.Value);
else
return null; // Because C# does not have NaN
}
...
var int1 = ParseInt("1.15"); // returns 1
var int2 = ParseInt("123abc456"); // returns 123
var int3 = ParseInt("abc"); // returns null
var int4 = ParseInt("123"); // returns 123
var int5 = ParseInt("-1.15"); // returns -1
var int6 = ParseInt("abc123"); // returns null
Upvotes: 0
Reputation: 3972
Just try this,
Int32 result =0;
Int32.TryParse(aTestRecord.aMecProp, out result);
Upvotes: 0
Reputation: 966
You can convert to double and then typecast it
string str = "1.15";
int val = (int)Convert.ToDouble(str);
Upvotes: 0
Reputation: 38638
That is because 1.xx
is not a integer valid value. You could truncate before converting to Int32
, for sample:
int result = (int)(Math.Truncate(double.Parse(aTestRecord.aMecProp)* value) / 100);
Upvotes: 1
Reputation: 8881
An integer can only represent strings without a decimal part. 1.15 contains a decimal part of 0.15. You have to convert it into a float to keep the decimal part and correctly parse it:
float f = Convert.ToSingle(aTestRecord.aMecProp);
Upvotes: 1
Reputation: 10156
Try this:
double i = Convert.ToDouble(aTestRecord.aMecProp);
Or if you want the integer part:
int i = (int) Convert.Double(aTestRecord.aMecProp);
Upvotes: 0
Reputation: 25370
if you are trying to validate that a string is an integer, use TryParse()
int i;
if (int.TryParse(aTestRecord.aMecProp, out i))
{
}
i
will get assigned if TryParse() is successful
Upvotes: 0