简体   繁体   中英

C# string to float to int coversion

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)

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.

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

You are parsing without specifying the IFormatProvider (eg 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 (eg 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.

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM