tags:

views:

61

answers:

1

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;
+5  A: 

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?

Jon Skeet
Thanks for explaining it, I've added the code I'm using from this into the original question, it works, but Is it the best way?
JoeBeez
@JoeBeez: Depending on exactly how you want the value to be rounded, and exactly how you want it to be parsed, yes. Think about different cultures, and values liker "76.6" and "76.5".
Jon Skeet