Javascript 如何在javascript中选择大整数中的第n位数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4654715/
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 do I select the nth digit in a large integer inside javascript?
提问by Simon Suh
When I want to select the nth character, I use the charAt() method, but what's the equivalent I can use when dealing with integers instead of string values?
当我想选择第 n 个字符时,我使用了 charAt() 方法,但是在处理整数而不是字符串值时我可以使用的等效方法是什么?
回答by Seth
Use String()
:
使用String()
:
var number = 132943154134;
// convert number to a string, then extract the first digit
var one = String(number).charAt(0);
// convert the first digit back to an integer
var one_as_number = Number(one);
回答by Christian
It's a stupid solution but seems to work without converting to string.
这是一个愚蠢的解决方案,但似乎无需转换为字符串即可工作。
var number = 123456789;
var pos = 4;
var digit = ~~(number/Math.pow(10,pos))- ~~(number/Math.pow(10,pos+1))*10;
回答by majelbstoat
You could convert the number to a string and do the same thing:
您可以将数字转换为字符串并执行相同的操作:
parseInt((number + '').charAt(0))
parseInt((number + '').charAt(0))
回答by metamatt
If you want an existing method, convert it to a string and use charAt.
如果您需要现有方法,请将其转换为字符串并使用 charAt。
If you want a method that avoids converting it to a string, you could play games with dividing it by 10 repeatedly to strip off enough digits from the right -- say for 123456789, if you want the 3rd-from-right digit (6), divide by 10 3 times yielding 123456, then take the result mod 10 yielding 6. If you want to start counting digits from the left, which you probably do, then you need to know how many digits (base 10) are in the entire number, which you could deduce from the log base 10 of the number... All this is unlikely to be any more efficient than just converting it to a string.
如果您想要一种避免将其转换为字符串的方法,您可以玩游戏,将其反复除以 10 以从右侧去除足够的数字 - 例如 123456789,如果您想要从右数第 3 个数字 (6) , 除以 10 3 次产生 123456,然后取结果 mod 10 产生 6。 如果你想从左边开始计算数字,你可能会这样做,那么你需要知道有多少个数字(基数为 10)在整个数字,您可以从数字的对数基数 10 中推导出来……所有这些都不太可能比将其转换为字符串更有效。
回答by Bastian Hofmann
function digitAt(val, index) {
return Math.floor(
(
val / Math.pow(10, Math.floor(Math.log(Math.abs(val)) / Math.LN10)-index)
)
% 10
);
};
digitAt(123456789, 0) // => 1
digitAt(123456789, 3) // => 4
A bit messy.
有点乱。
Math.floor(Math.log(Math.abs(val)) / Math.LN10)
Calculates the number of digits (-1) in the number.
计算数字中的位数 (-1)。
回答by Kareem
var number = 123456789
function return_digit(n){
r = number.toString().split('')[n-1]*1;
return r;
}
return_digit(3); /* returns 3 */
return_digit(6); /* returns 6 */
回答by daniel
var num = 123456;
var secondChar = num.toString()[1]; //get the second character