C#将包含浮点的字符串转换为整数 [英] C# Converting a string containing a floating point to an integer

查看:665
本文介绍了C#将包含浮点的字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串(例如可以为空或包含"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.

推荐答案

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

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

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

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

最好使用 IFormatProvider 并将其转换为从当前区域性设置中以独立的方式编号:

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

解决方案3:解析&分割

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

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

或者:

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

注释

  • 如果要处理空字符串和空字符串,请编写方法并添加字符串. IsNullOrEmpty 条件.
  • 要获取当前区域性设置的小数点分隔符,可以使用四舍五入到避免陷阱.
  • 选择强制转换,ParseTryParse Convert 明智地上课.在以下位置了解更多信息:
    • 如何:将字符串转换为int(《 C#编程指南》)
    • 如何:确定字符串是否代表数值(C#编程指南)
    • 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)
        • 这篇关于C#将包含浮点的字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆