如何在.net中将long转换为int?
我正在开发silverlight中的window phone 7应用程序。 我是窗口手机7应用程序的新手。 我有String格式的long值如下
String Am = AmountTextBox.Text.ToString()
上面代码中的AmountTextBox.Text.ToString()是long值,它是字符串格式。 我想在我的应用程序中存储15位数的值。
我找到了以下转换链接。
我可以将long转换为int吗?
我应该如何将字符串格式的long值转换为int? 能否请您提供我可以解决上述问题的任何代码或链接? 如果我做错了什么,请指导我。
您不能存储15位整数,因为整数的最大值是2,147,483,647。
long
值有什么问题?
您可以使用TryParse()从您的用户输入中获取long
-Value:
String Am = AmountTextBox.Text.ToString(); long l; Int64.TryParse(Am, out l);
如果文本无法转换为long
,它将返回false
,因此使用起来非常安全。
否则,将long
转换为int
很容易
int i = (int)yourLongValue;
如果您对丢弃MSB并使用LSB感到高兴。
使用Convert.ToInt32() 。 如果值对于int来说太大,那么它将抛出OverflowException。
此方法可以采用整个范围的值,包括Int64和字符串。
您有一个以string
forms存储的数字,并且您希望将其转换为数字类型。
您无法将其转换为int
类型(也称为Int32
),因为正如其他答案所提到的那样,该类型没有足够的范围来存储您的预期值。
相反,您需要将值转换为long
(也称为Int64
)。 最简单,最无痛的方法是使用TryParse
方法 ,该方法将数字的字符串表示forms转换为其等效的64位有符号整数。
使用此方法(而不是像Parse
这样的方法)的优点是,如果转换失败,它不会抛出exception。 由于例外情况很昂贵,除非绝对必要,否则应避免抛弃它们。 相反,您指定包含要转换为该方法的第一个参数的数字的字符串,以及在转换成功时接收转换后的数字的out
值。 返回值是一个布尔值,表示转换是否成功。
示例代码:
private void ConvertNumber(string value) { Int64 number; // receives the converted numeric value, if conversion succeeds bool result = Int64.TryParse(value, out number); if (result) { // The return value was True, so the conversion was successful Console.WriteLine("Converted '{0}' to {1}.", value, number); } else { // Make sure the string object is not null, for display purposes if (value == null) { value = String.Empty; } // The return value was False, so the conversion failed Console.WriteLine("Attempted conversion of '{0}' failed.", value); } }
C#中的最大Int32
值为2,147,483,647,比您需要的15位数短。
您确定需要将此值转换为int吗? 听起来你最好将值存储在long
,或者将其保留为String
。
Long值存储的数据多于Integer 32值,因此如果要保留所有15位数,则无法转换为标准Integer。
但是除了你想要使用的’which’数据类型之外,Convert类应该可以帮助你,即Convert.ToInt64,它可以做你想要的
在C# int
有32位, long
有64位。 因此long
所有值都不能为int
。 也许得到一个int
数组?
public static int[] ToIntArray(long l) { var longBytes = BitConverter.GetBytes(l); // Get integers from the first and the last 4 bytes of long return new int[] { BitConverter.ToInt32(longBytes, 0), BitConverter.ToInt32(longBytes, 4) }; }