C# 如何获取数字的最后一位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15731716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the last digit of a number
提问by mns
How to get the last digit of a number? e.g. if 1232123, 3 will be the result
如何获取数字的最后一位?例如,如果 1232123,则结果为 3
Some efficient logic I want so that it is easy for results having big numbers.
After the final number I get, I need to some processing in it.
我想要一些有效的逻辑,以便很容易获得大数字的结果。
在我得到最终数字之后,我需要对其进行一些处理。
回答by acrilige
Just take mod 10:
只需使用 mod 10:
Int32 lastNumber = num % 10;
One could use Math.Abs if one's going to deal with negative numbers. Like so:
如果要处理负数,可以使用 Math.Abs。像这样:
Int32 lastNumber = Math.Abs(num) % 10;
回答by Stochastically
It's just the number modulo 10. For example in C
它只是数字模 10。例如在 C
int i = 1232123;
int lastdigit = (i % 10);
回答by Aaron Anodide
Here's the brute force way that sacrifices efficiency for obviousness:
这是为了显而易见而牺牲效率的蛮力方式:
int n = 1232123;
int last = Convert.ToInt32(n.ToString()
.AsEnumerable()
.Last()
.ToString());
回答by Atanas Tankov
The best way to do this is int lastNumber = (your number) % 10;
And if you want to return the last digit as string you can do this
最好的方法是int lastNumber = (your number) % 10;
如果你想将最后一位数字作为字符串返回,你可以这样做
switch (number % 10)
{
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
}
回答by Adarsh Babu PR
Another way is..
另一种方式是..
var digit = Convert.ToString(1234);
var lastDigit = digit.Substring(digit.Length - 1);
回答by TheChilliPL
The best would be:
最好的是:
Math.Abs(num % 10);
Cause num % 10
will give you negative result for negative numbers
原因num % 10
会给你负数的负结果