Search code examples
c#parsingfloating-pointint

C# Converting a string containing a floating point to an integer


What is the best way to take a string which can be empty or contain "1.2" for example, and convert it to an integer? int.TryParse fails, of course, and I don't want to use float.TryParse and then convert to int.


Solution

  • Solution 1: Convert.ToDouble (culture-dependent)

    You may use Convert.ToDouble. But, beware! The below solution will work only when the number separator in the current culture's setting is a period character.

    var a = (int)Convert.ToDouble("1.2");    
    

    Solution 2: Convert.ToDouble (culture-independent)

    It's preferable to use IFormatProvider and convert the number in an independent way from the current culture settings:

    var a = (int)Convert.ToDouble("1.2", CultureInfo.InvariantCulture.NumberFormat); 
    

    Solution 3: Parse & Split

    Another way to accomplish this task is to use Split on parsed string:

    var a = int.Parse("1.2".Split('.')[0]);
    

    Or:

    var a = int.Parse("1.2".Split('.').First());
    

    Notes