Ste*_*eve 149
如果没有转换为字符串,您可以尝试:
Math.Ceiling(Math.Log10(n));
Run Code Online (Sandbox Code Playgroud)
ysap评论后的更正:
Math.Floor(Math.Log10(n) + 1);
Run Code Online (Sandbox Code Playgroud)
And*_*iih 75
试试这个:
myint.ToString().Length
Run Code Online (Sandbox Code Playgroud)
那样有用吗 ?
sɐu*_*qɐp 30
任何这些扩展都可以完成这项工作:
public static class Int32Extensions
{
// IF-CHAIN:
public static int Digits_IfChain(this int n)
{
n = Math.Abs(n);
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
return 10;
}
// LOG10:
public static int Digits_Log10(this int n) =>
n == 0 ? 1 : 1 + (int)Math.Log10(Math.Abs(n));
// WHILE:
public static int Digits_While(this int n)
{
int digits = 0;
do { ++digits; n /= 10; } while (n != 0);
return digits;
}
// STRING:
public static int Digits_String(this int n) =>
n >= 0 ? n.ToString().Length : n.ToString().Length - 1;
}
Run Code Online (Sandbox Code Playgroud)
我在5个不同的场景中对这些进行了一些性能测试,在for循环中进行了100.000.000次调用Int32.
最终获胜者是 ...
public static class Int64Extensions
{
// IF-CHAIN:
public static int Digits_IfChain(this long n)
{
n = Math.Abs(n);
if (n < 10L) return 1;
if (n < 100L) return 2;
if (n < 1000L) return 3;
if (n < 10000L) return 4;
if (n < 100000L) return 5;
if (n < 1000000L) return 6;
if (n < 10000000L) return 7;
if (n < 100000000L) return 8;
if (n < 1000000000L) return 9;
if (n < 10000000000L) return 10;
if (n < 100000000000L) return 11;
if (n < 1000000000000L) return 12;
if (n < 10000000000000L) return 13;
if (n < 100000000000000L) return 14;
if (n < 1000000000000000L) return 15;
if (n < 10000000000000000L) return 16;
if (n < 100000000000000000L) return 17;
if (n < 1000000000000000000L) return 18;
return 19;
}
// LOG10:
public static int Digits_Log10(this long n) =>
n == 0L ? 1 : 1 + (int)Math.Log10(Math.Abs(n));
// WHILE:
public static int Digits_While(this long n)
{
int digits = 0;
do { ++digits; n /= 10L; } while (n != 0L);
return digits;
}
// STRING:
public static int Digits_String(this long n) =>
n >= 0L ? n.ToString().Length : n.ToString().Length - 1;
}
Run Code Online (Sandbox Code Playgroud)
最丑陋的事!
ysa*_*sap 13
不是直接C#,但公式是: n = floor(log10(x)+1)
答案已经在这里适用于无符号整数,但我没有找到很好的解决方案来获取小数和双精度数字.
public static int Length(double number)
{
number = Math.Abs(number);
int length = 1;
while ((number /= 10) >= 1)
length++;
return length;
}
//number of digits in 0 = 1,
//number of digits in 22.1 = 2,
//number of digits in -23 = 2
Run Code Online (Sandbox Code Playgroud)
如果精度很重要,您可以将输入类型更改double为decimal,但十进制也有限制.
这是一个适用于否定的更新版本:
int digits = n == 0 ? 1 : Math.Floor(Math.Log10(Math.Abs(n)) + 1)
Run Code Online (Sandbox Code Playgroud)
小智 5
使用递归(有时在访谈时询问)
public int CountDigits(int number)
{
// In case of negative numbers
number = Math.Abs(number);
if (number >= 10)
return CountDigits(number / 10) + 1;
return 1;
}
Run Code Online (Sandbox Code Playgroud)