简体   繁体   中英

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

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

Use 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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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