简体   繁体   English

如何在javascript内的大整数中选择第n位?

[英]How do I select the nth digit in a large integer inside javascript?

当我想选择第n个字符时,我使用charAt()方法,但在处理整数而不是字符串值时,我可以使用什么?

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); 

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;

您可以将数字转换为字符串并执行相同的操作:

parseInt((number + '').charAt(0))

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,如果你想要从右到右的数字(6)除以10 3次得到123456,然后得到结果mod 10得到6.如果你想从左边开始计算你可能做的数字,那么你需要知道整个数字(基数10)数字,您可以从数字的日志基数10中推断出......所有这些都不可能比将其转换为字符串更有效。

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)。

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 */
var num = 123456;
var secondChar = num.toString()[1]; //get the second character

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM