C# 将包含浮点数的字符串转换为整数

发布于 2024-09-12 18:52:08 字数 135 浏览 11 评论 0原文

例如,获取可以为空或包含“1.2”的字符串并将其转换为整数的最佳方法是什么? int.TryParse 当然会失败,我不想使用 float.TryParse 然后转换为 int

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

忱杏 2024-09-19 18:52:08

解决方案 1:Convert.ToDouble(取决于文化)

您可以使用 Convert.ToDouble。但是,要小心!仅当当前区域性设置中的数字分隔符是句点字符时,以下解决方案才有效。

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

解决方案 2:Convert.ToDouble(文化无关)

最好使用 IFormatProvider 并以独立于当前区域性设置的方式转换数字:

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

解决方案 3:解析和转换Split

完成此任务的另一种方法是对解析的字符串使用 Split:

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

或者:

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

注意

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

酷到爆炸 2024-09-19 18:52:08

我不知道解析为 float 并转换为 int 有什么问题。我怀疑任何其他方式都会更有效,但这里有一个尝试:

//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;
 }

为了全球化代码,您需要将 "." 替换为 System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

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.

真心难拥有 2024-09-19 18:52:08
int a = (int)Math.Round(float.Parse("0.9"));

您需要先对其进行舍入,除非您希望将 0.9f 转换为 0 而不是 1。

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.

跨年 2024-09-19 18:52:08

也许您可以尝试使用字符串函数删除浮点之后的所有内容,然后转换为 int。但说实话,我认为这并不比转换为 float 然后再转换为 int 更好。

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.

梦开始←不甜 2024-09-19 18:52:08

我认为另一种方法是将字符串分割成小数点(.)作为分隔符,然后解析整数。当然,我还没有问您该字符串是否可能包含类似 “37.56 英里 in 32.65 秒” 类型的值。

考虑到字符串中只有一个值(字符串或数字),我可以想到以下行中的内容:

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

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]);
}
分开我的手 2024-09-19 18:52:08

您可以使用 Visual Basic 运行时库在 C# 中完成此操作。

您需要将对程序集 Microsoft.VisualBasic.dll 的引用添加到您的解决方案中。

然后以下代码将完成您的转换:

using VB = Microsoft.VisualBasic.CompilerServices;

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

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");
    }
}
━╋う一瞬間旳綻放 2024-09-19 18:52:08

我遇到了同样的问题,最终使用了 Mark 和 Dariusz 的混合体:

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

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文