Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Nir Avatar asked Aug 03 '10 09:08

Nir


1 Answers

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)
like image 188
Dariusz Woźniak Avatar answered Oct 04 '22 11:10

Dariusz Woźniak