有没有办法检查整数变量的长度,如果是长只是修剪它.我在数据库中有一个接受3个字符的字段,lenth是3.
所以它可以像使用字符串变量一样完成
例:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Run Code Online (Sandbox Code Playgroud)
谢谢!
小智 21
最简单的答案是:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
Run Code Online (Sandbox Code Playgroud)
小智 11
以下对我来说是一种享受!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Run Code Online (Sandbox Code Playgroud)
原始资料来源:http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
您不必将其转换为字符串以使其更短,这可以通过数字方式完成:
if (num > 999) {
num %= 1000;
}
Run Code Online (Sandbox Code Playgroud)
如果您想从右侧剪切数字,这将从左侧剪切数字:
while (num > 999) {
num /= 10;
}
Run Code Online (Sandbox Code Playgroud)
如果该值可能为负数,还请检查:
if (num < -99) {
num = -(-num % 100);
}
Run Code Online (Sandbox Code Playgroud)
或者:
while (num < -99) {
num = -(-num / 10);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58871 次 |
| 最近记录: |