JoeBeez
JoeBeez

Reputation: 311

C# Convert string to int (with rounding)

What's the easiest way to get a string with the value of "76.10" into an int rounded to 76?

I've tried a few different ways using Convert.ToInt32 and Decimal but I can't seem to get it right?

Edit: Here's the code Jon helped me with:

            decimal t = Math.Round(decimal.Parse(info.HDDStatus));
            int v = (int)t;

Upvotes: 2

Views: 6783

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273844

  1. Convert it to double first and use Math.Floor()

  2. Extract the substring (76) first .

 

string s = "76.7"; 
int n = int.Parse(s.Substring(0, s.IndexOf('.')));

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503859

The simplest way would be to use Decimal.Parse to parse it, and then Math.Round (or potentially Math.Floor depending on how you want numbers like "76.7" to be handled) to round it. Then convert to an integer just by casting.

I would suggest using decimal rather than double as you're inherently talking about a decimal number (as that's how it's represented in text).

The exact method of parsing will depend on culture - would you expect text of "76,10" to appear in a European context, or will it always use "." as the decimal point, for example?

Upvotes: 8

Related Questions