C#字符串转换为整数并比较
您好,我在将字符串转换为int时遇到此错误C#字符串转换为整数并比较,c#,asp.net,C#,Asp.net,您好,我在将字符串转换为int时遇到此错误 string oneamount = "1200.12366"; string twoamount = "121.11"; int x=Int32.Parse(oneamount); int y = Int32.Parse(twoamount); if (x > y) { Console.WriteLine(&q
string oneamount = "1200.12366";
string twoamount = "121.11";
int x=Int32.Parse(oneamount);
int y = Int32.Parse(twoamount);
if (x > y)
{
Console.WriteLine("okay");
}
错误
输入字符串的格式不正确无法解释@MichaelRandall的评论 整数为整数/无小数位数。如果要与十进制进行比较,请使用
double、float、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");
}
请尝试Int32.TryParse函数。它将数字的字符串表示形式转换为其等效的32位有符号整数。返回值指示操作是否成功
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");
}
签名为:
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.
第一个问题是你知道整数是什么吗?@MichaelRandall是的,我知道整数是什么?我可以向你保证它不是,现在下一个问题是它是什么类型的?如何解决这个问题?补充了一个解释@MichaelRandall评论的答案