简体   繁体   中英

How do I parse a decimal number from a string to an integer in C#?

I want to convert a decimal string to an integer but I keep getting the following error:

System.FormatException: Input string was not in a correct format.

var myString = "18.7";
var myInteger = Int32.Parse(myString); //flaging an error here
Console.WriteLine(myInteger) //desired result = 18

You should parse it to a double type and cast it to an integer

var myString = "18.7";
var myInteger = (int)Convert.ToDouble(myString); 
Console.WriteLine(myInteger) //desired result = 18

The conversion will be like this

  • "18.7" (a string value) to 18.7 (a double value)
  • 18.7 (a double type) to 18 (an integer type - the decimal part gets removed)

In some cases, your strings may be like 18,7 which is relied on CultureInfo for conversion. That makes 18.7 unformattable.

As for culture independency, you can convert it like below

var myString = "18.7";
var myInteger = (int)Convert.ToDouble(myString,CultureInfo.InvariantCulture.NumberFormat); 
Console.WriteLine(myInteger) //desired result = 18

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM