0

What is the best way for converting string (decimal number) into integer in C#?
In my case, message is a string with coordinates that are separated with {x:y} This is not working for me (don't know why):

string[] coordinates = Regex.Split(message, "{x:y}");
int coord_X = (int) float.Parse(coordinates[0]);
int coord_Y = (int) float.Parse(coordinates[1]);

Message is equal to: -5.5707855{x:y}0.8193512{x:y}
coord_X is -55707855 (should be -5.5707855)
coord_Y is 8193512 (should be 0.8193512)

3
  • 1
    Aehm, an integer number doesn't contain any decimal Commented Dec 29, 2013 at 13:49
  • Divide them by 10.000.000 and don't cast them to int? Commented Dec 29, 2013 at 13:49
  • But i tried your code coord_X was -5 and coord_Y was 0. you don't need to convert it to int. Commented Dec 29, 2013 at 16:37

4 Answers 4

1

Int doesn't support decimals. You can either use decimal, float or double.

There are several ways to convert those Types.

Take a look at the Convert class.

Sign up to request clarification or add additional context in comments.

Comments

1

The Int datatype cannot contain a fractional part. Try this

var message = "-5.5707855{x:y}0.8193512{x:y}";
string[] coordinates = Regex.Split(message, "{x:y}");
var coord_X = float.Parse(coordinates[0]); // or decimal.Parse
var coord_Y = float.Parse(coordinates[1]); // or decimal.Parse

console.WriteLine(coord_X); // -5.5707855
console.WriteLine(coord_Y); // 0.8193512

Comments

0

Using regular expressions:

      string s = "-5.5707855{x:y}0.8193512{x:y}";
      MatchCollection matchCollection = Regex.Matches( s, @"(.+?)\{x:y}", RegexOptions.None );
      double coord_X = double.Parse( matchCollection[ 0 ].Groups[ 1 ].Value );
      double coord_Y = double.Parse( matchCollection[ 1 ].Groups[ 1 ].Value );

Comments

0

You are parsing without specifying the IFormatProvider (e.g. CultureInfo). The point char in your string input might be interpreted as thousand separator (instead of decimal) if the locale of your machine is set this way (e.g. Italian, French, etc...). In that case the Parse method would (correctly) return 55 millions etc instead of 5.5 etc... To control all these details explicilty I suggest you use this overload of Parse:

public static float Parse(
    string s,
    NumberStyles style,
    IFormatProvider provider
)

If you need to go from float to int I prefer doing a conversion instead of a cast (for clarity):

int coord_X = Convert.ToInt32(float.Parse(lines[0]));

Being an int, coord_X will be rounded to the nearest integral number.

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.