1

How do I convert a string containing a decimal number to nearest integer value?

For example:

string x = "4.72";

I want to get 5 as integer.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Furkan
  • 39
  • 7

1 Answers1

1

It is not clear that either you want to round or get the ceiling value but we have Math class which provides the basic methods to extract the floor value using Floor() method or ceiling value using Ceiling() or rounded value using the Round() like:

string x = "4.72";
Console.WriteLine(Math.Ceiling(Convert.ToDecimal(x)));
Console.WriteLine(Math.Floor(Convert.ToDecimal(x)));
Console.WriteLine(Math.Round(Convert.ToDecimal(x)));

Output:

5

4

5

Please see this working DEMO Fiddle.

Note: for cases where we want the math convention for rounding the decimal points then we should always be calling the Math.Round().

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • right. ceiling will always move the number to the next, but round would change 4.5 to 4. depending on the required logic math.round might be enough, but if you require for 4.5 to move to 5, then you need Ceiling – Mike Jul 05 '18 at 14:49
  • It's probably safe to say you want to use the 3rd line. Math.Round uses the most commonly held practice of rounding .5 up. ex. 1.5 = 2. – Jason Geiger Jul 05 '18 at 14:51
  • It gets 5 as decimal i want to assign it a int variable. Lİke: string x = "4.72"; int y= (int)Math.Round(Convert.ToDecimal(x)); But i get 472 as result. – Furkan Jul 06 '18 at 06:44
  • You will need to convert it to integer back – Ehsan Sajjad Jul 06 '18 at 10:08
  • 1
    @Mike there is also an overload with a MidpointRounding parameter. `MidpointRounding.AwayFromZero` would round 4.5 to 5. – Hans Kesting Jul 06 '18 at 10:30
  • 1
    @Furkan you are working in a culture where the decimal is a comma (and the `.` is just a grouping separator). Specify `CultureInfo.InvariantCulture` in the Convert – Hans Kesting Jul 06 '18 at 10:31
  • @HansKesting yes i replaced point with comma and it solved my problem. Thank you sir. – Furkan Jul 06 '18 at 14:14