开发者

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 开发者_Python百科fails, of course, and I don't want to use float.TryParse and then convert to int.


Solution 1: Convert.ToDouble (culture-dependent)

You may using 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

  • If you want to handle empty and null strings, write a method and add string.IsNullOrEmpty condition.
  • To get decimal separator for the current culture setting, you can use NumberFormatInfo.NumberDecimalSeparator property.
  • You should also keep eye on rounding to avoid traps.
  • Select casting, Parse, TryParse or Convert class wisely. Read more at:
    • How to: Convert a string to an int (C# Programming Guide)
    • How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)


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.


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.


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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜