嗨,我在将字符串转换为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");
}
错误 输入的字符串格式不正确
答案 0 :(得分:1)
请尝试使用Int32.TryParse函数。它将数字的字符串表示形式转换为其等效的32位带符号整数。返回值指示操作是否成功。
签名为:
public static bool TryParse (string s, out int result);
示例:
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.
一旦整数中的值正确,就可以将它们进行比较以查看操作是否成功。
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");
}
答案 1 :(得分:0)
阐述@MichaelRandall的评论。
整数是整数/无小数位。如果要与十进制进行比较,请使用double, float, decimal
出于精确的目的,您可以将string
的值转换为decimal
string oneamount = "1200.12366";
string twoamount = "121.11";
var x = Convert.ToDecimal(oneamount);
var y = Convert.ToDecimal(twoamount);
if (x > y)
{
Console.WriteLine("okay");
}