JavaScript:从数字中获取第二个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13955738/
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
JavaScript: Get the second digit from a number?
提问by user1856596
I have a number assigned to a variable, like that:
我有一个分配给变量的数字,如下所示:
var myVar = 1234;
Now I want to get the second digit (2 in this case) from that number without converting it to a string first. Is that possible?
现在我想从该数字中获取第二个数字(在本例中为 2),而无需先将其转换为字符串。那可能吗?
回答by Denys Séguret
So you want to get the second digit from the decimal writing of a number.
所以你想从一个数字的十进制书写中得到第二个数字。
The simplest and most logical solution is to convert it to a string :
最简单和最合乎逻辑的解决方案是将其转换为字符串:
var digit = (''+myVar)[1];
or
或者
var digit = myVar.toString()[1];
If you don't want to do it the easy way, or if you want a more efficient solution, you can do that :
如果您不想以简单的方式进行操作,或者想要更有效的解决方案,则可以这样做:
var l = Math.pow(10, Math.floor(Math.log(myVar)/Math.log(10))-1);
var b = Math.floor(myVar/l);
var digit = b-Math.floor(b/10)*10;
For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.
对于对表演感兴趣的人,我做了一个jsperf。对于像我一样使用日志的随机数是迄今为止最快的解决方案。
回答by Gerges Beshay
1st digit of number from right → number % 10= Math.floor((number / 1) % 10)
数字的第 1 位数字 → number % 10=Math.floor((number / 1) % 10)
1234 % 10; // 4
Math.floor((1234 / 1) % 10); // 4
2nd digit of number from right → Math.floor((number / 10) % 10)
数字的第 2 位数字 → Math.floor((number / 10) % 10)
Math.floor((1234 / 10) % 10); // 3
3rd digit of number from right → Math.floor((number / 100) % 10)
数字的第 3 位数字 → Math.floor((number / 100) % 10)
Math.floor((1234 / 100) % 10); // 2
nth digit of number from right → Math.floor((number / 10^n-1) % 10)
数字的第 n 位数字 → Math.floor((number / 10^n-1) % 10)
function getDigit(number, n) {
return Math.floor((number / Math.pow(10, n - 1)) % 10);
}
number of digits in a number → Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1Credit to: https://stackoverflow.com/a/28203456/6917157
数字中的位数 →Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1归功于:https: //stackoverflow.com/a/28203456/6917157
function getDigitCount(number) {
return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}
nthdigit of number from left or right
从左数或从右数的第 n位数字
function getDigit(number, n, fromLeft) {
const location = fromLeft ? getDigitCount(number) + 1 - n : n;
return Math.floor((number / Math.pow(10, location - 1)) % 10);
}
回答by Vikdor
Get rid of the trailing digits by dividing the number with 10 till the number is less than 100, in a loop. Then perform a modulo with 10 to get the second digit.
通过将数字除以 10 直到数字小于 100,以循环方式去除尾随数字。然后用 10 取模得到第二个数字。
if (x > 9) {
while (x > 99) {
x = (x / 10) | 0; // Use bitwise '|' operator to force integer result.
}
secondDigit = x % 10;
}
else {
// Handle the cases where x has only one digit.
}
回答by paulsm4
A "number" is one thing.
“数字”是一回事。
The representationof that number (e.g. the base-10 string "1234") is another thing.
该数字的表示(例如,基数为 10 的字符串“1234”)是另一回事。
If you want a particular digit in a decimal string ... then your best bet is to get it from a string :)
如果您想要十进制字符串中的特定数字......那么您最好的选择是从字符串中获取它:)
Q: You're aware that there are pitfalls with integer arithmetic in Javascript, correct?
问:您知道 Javascript 中的整数运算存在缺陷,对吗?
Q: Why is it so important to not use a string? Is this a homework assignment? An interview question?
问:为什么不使用字符串如此重要?这是家庭作业吗?面试题?
回答by mutenka
function getNthDigit(val, n){
//Remove all digits larger than nth
var modVal = val % Math.pow(10,n);
//Remove all digits less than nth
return Math.floor(modVal / Math.pow(10,n-1));
}
// tests
[
0,
1,
123,
123456789,
0.1,
0.001
].map(v =>
console.log([
getNthDigit(v, 1),
getNthDigit(v, 2),
getNthDigit(v, 3)
]
)
);
回答by Chris Schmitz
You know, I get that the question asks for how to do it without a number, but the title "JavaScript: Get the second digit from a number?" means a lot of people will find this answer when looking for a way to get a specific digit, period.
你知道,我知道这个问题问的是如何在没有数字的情况下做到这一点,但标题是“JavaScript:从数字中获取第二个数字?” 意味着很多人在寻找获得特定数字、句点的方法时会找到这个答案。
I'm not bashing the original question asker, I'm sure he/she had their reasons, but from a search practicality standpoint I think it's worth adding an answer here that does convert the number to a string and back because, if nothing else, it's a much more terse and easy to understand way of going about it.
我不是在抨击最初的提问者,我相信他/她有他们的理由,但从搜索实用性的角度来看,我认为值得在此处添加一个答案,将数字转换为字符串并返回,因为如果没有别的,这是一种更简洁、更容易理解的方法。
let digit = Number((n).toString().split('').slice(1,1))
// e.g.
let digit = Number((1234).toString().split('').slice(1,1)) // outputs 2
Getting the digit without the string conversion is great, but when you're trying to write clear and concise code that other people and future you can look at really quick and fully understand, I think a quick string conversion one liner is a better way of doing it.
在没有字符串转换的情况下获得数字很棒,但是当您尝试编写清晰简洁的代码时,其他人和未来您可以非常快速和完全理解,我认为快速字符串转换单行是更好的方法正在做。
回答by Raghav
I don't know why you need this logic, but following logic will get you the second number
我不知道你为什么需要这个逻辑,但遵循逻辑会给你第二个数字
<script type="text/javascript">
var myVal = 58445456;
var var1 = new Number(myVal.toPrecision(1));
var var2 = new Number(myVal.toPrecision(2));
var rem;
rem = var1 - var2;
var multi = 0.1;
var oldvalue;
while (rem > 10) {
oldvalue = rem;
rem = rem * multi;
rem = rem.toFixed();
}
alert(10-rem);
</script>
回答by Coaxial
function getDigit(number, indexFromRight) {
var maxNumber = 9
for (var i = 0; i < indexFromRight - 2; i++) {
maxNumber = maxNumber * 10 + 9
}
if (number > maxNumber) {
number = number / Math.pow(10, indexFromRight - 1) | 0
return number % 10
} else
return 0
}
回答by Jamie Hutber
Just a simple idea to get back any charter from a number as a string or int:
只是一个简单的想法,从一个数字作为字符串或整数取回任何宪章:
const myVar = 1234;
String(myVar).charAt(1)
//"2"
parseInt(String(myVar).charAt(1))
//2
回答by simonthumper
var newVar = myVar;
while (newVar > 100) {
newVar /= 10;
}
if (newVar > 0 && newVar < 10) {
newVar = newVar;
}
else if (newVar >= 10 && newVar < 20) {
newVar -= 10;
}
else if (newVar >= 20 && newVar < 30) {
newVar -= 20;
}
else if (newVar >= 30 && newVar < 40) {
newVar -= 30;
}
else if (newVar >= 40 && newVar < 50) {
newVar -= 40;
}
else if (newVar >= 50 && newVar < 60) {
newVar -= 50;
}
else if (newVar >= 60 && newVar < 70) {
newVar -= 60;
}
else if (newVar >= 70 && newVar < 80) {
newVar -= 70;
}
else if (newVar >= 80 && newVar < 90) {
newVar -= 80;
}
else if (newVar >= 90 && newVar < 100) {
newVar -= 90;
}
else {
newVar = 0;
}
var secondDigit = Math.floor(newVar);
That's how I'd do it :)
我就是这样做的:)
And here's a JSFiddle showing it works :) http://jsfiddle.net/Cuytd/
这是一个显示它有效的 JSFiddle :) http://jsfiddle.net/Cuytd/
This is also assuming that your original number is always greater than 9... If it's not always greater than 9 then I guess you wouldn't be asking this question ;)
这也是假设你的原始数字总是大于 9...如果它不总是大于 9 那么我猜你不会问这个问题;)

