18

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.

5
  • 4
    Appart parsing it to a float and then rouding it, I don't see how you could do that...
    – Philippe
    Aug 3, 2010 at 10:01
  • 1
    (int)float.Parse("1.2") - it isn't too much work. Ruby does this though - "1.234".to_i yields 1
    – Gishu
    Aug 3, 2010 at 10:07
  • 1
    @Gishu ... and VB6 does this Int("1.234") yields 1. But the question is about C#.
    – MarkJ
    Aug 3, 2010 at 10:22
  • @MarkJ - yup I noticed.. that's why I just upvoted Phillipe.. parse and cast seems to be the way to do it in C#. The answers below all seem to be much more work in comparison.
    – Gishu
    Aug 3, 2010 at 10:34
  • @MarkJ: FYI VB.NET accepts this syntax too but e.g. Int(1.000000) returns 1000000 as integer result (might have to do with the fact, that in my country , is the default separator, but still worth noting). Edit: Convert.ToDouble does the same, so this is "just" an issue with the Culture-NumberFormat ...
    – Levite
    Mar 6, 2015 at 10:48

7 Answers 7

42

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

1
  • 2
    +1. Especially for saying that Convert.ToDouble uses the decimal delimiter from the thread culture settings (by default the Windows regional settings), and it can be a comma. You can force it to use a dot by passing CultureInfo.InvariantCulture.NumberFormat
    – MarkJ
    Aug 3, 2010 at 10:20
5

I don't know what's wrong with parsing to a float and converting to an int. I doubt that any other way would be more efficient but here's an attempt:

//allows empty strings and floating point values
int ParseInt(string s, bool alwaysRoundDown = false)
 {
    //converts null/empty strings to zero
    if (string.IsNullOrEmpty(s)) return 0;

    if (!s.Contains(".")) return int.Parse(s);

    string parts = s.Split(".");
    int i = int.Parse(parts[0]);
    if (alwaysRoundDown || parts.Length==1) return i;

    int digitAfterPoint = int.Parse(parts[1][0]);
    return (digitAfterPoint < 5) ? i : i+1;
 }

In order to globalize the code you would need to replace "." with System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.

3
  • Don't forget that the decimal delimiter can be different depending on regional settings.
    – MarkJ
    Aug 3, 2010 at 10:18
  • I added a note about globalization. Thanks! Aug 3, 2010 at 10:40
  • Undoubtedly the best one, @Mark. +1 from my side.
    – Kangkan
    Aug 3, 2010 at 12:12
2
int a = (int)Math.Round(float.Parse("0.9"));

You need to round it first unless you want 0.9f being converted to 0 instead of 1.

1

Maybe you can try to delete everything after floating point using string functions and then convert to int. But seriously I don't think it's better than converting to float and then to int.

2
  • If you do it that way, don't forget that the decimal delimiter is different on different regional settings. Our French cousins use ,
    – MarkJ
    Aug 3, 2010 at 10:16
  • Of course, I thought it was obvious :) In Russia we use commas as well.
    – fuwaneko
    Aug 3, 2010 at 10:32
0

I think another way of doing it would be splitting the string into pieces taking the decimal (.) as the delimiter and then parsing for the integer. Of course, I am yet to ask you if the string might contain values like "37.56 miles in 32.65 seconds" type values.

Considering there will be only one value (string or number) in the string, I can think of something in the following line:

public int64 GetInt64(string input)
{
    if (string.IsNullOrEmpty(input)) return 0;
    // Split string on decimal (.)
    // ... This will separate all the digits.
    //
    string[] words = input.Split('.');
    return int.Parse(words[0]);
}
1
  • Perhaps no need for int64 return when doing an int32 parse.
    – btlog
    Aug 3, 2010 at 10:13
0

You can use the Visual Basic runtime Library to accomplish this from c#.

You need to add a reference to the assembly Microsoft.VisualBasic.dll to your solution.

Then the following code will do your conversion:

using VB = Microsoft.VisualBasic.CompilerServices;

class Program
{
    static void Main(string[] args)
    {
        int i = VB.Conversions.ToInteger("1.2");
    }
}
0

I had this same problem and ended up using a hybrid of Mark's and Dariusz':

 if (num == "")
     {
      num = "0.00";
     }

  var num1 = (float)Convert.ToDouble(num);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.