-2

enter image description here

hi im getting this error while converting strings to int

string oneamount = "1200.12366";
string twoamount = "121.11";
int x=Int32.Parse(oneamount);
int y = Int32.Parse(twoamount);

      
            if (x > y)
            {
                Console.WriteLine("okay");
            }

Error input string was not in correct format

Raju Lama
  • 5
  • 4

2 Answers2

1

Please try Int32.TryParse function. It converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

Int32.TryParse Method

Signature is:

public static bool TryParse (string s, out int result);

Example:

using System;

public class Example
{
   public static void Main()
   {
      String[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = Int32.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine("Converted '{0}' to {1}.", value, number);
         }
         else
         {
            Console.WriteLine("Attempted conversion of '{0}' failed.",
                               value ?? "<null>");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.

Once you have correct value in your integer, then you can compare them to see whether or nor your operation succeeded.

string oneamount = "1200.12366";
int oneAmountInt32;
string twoamount = "121.11";
int twoAmountInt32;
Int32.TryParse(oneamount, out oneAmountInt32);
Int32.TryParse(twoamount, out twoAmountInt32);

      
if (oneAmountInt32 > twoAmountInt32)
{
    Console.WriteLine("okay");
}
fluidguid
  • 1,511
  • 14
  • 25
0

expounding on @MichaelRandall's comment.

Integers are whole number/no decimal place. If you want to compare with decimal, use double, float, decimal

you can convert the string values into decimal for precision purposes

string oneamount = "1200.12366";
string twoamount = "121.11";
var x = Convert.ToDecimal(oneamount);
var y = Convert.ToDecimal(twoamount);

      
            if (x > y)
            {
                Console.WriteLine("okay");
            }
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
Gabriel Llorico
  • 1,783
  • 1
  • 13
  • 23