开发者

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

开发者 https://www.devze.com 2023-02-03 19:07 出处:网络
When I want to select the nth character, I use the charAt() method, but what\'s the equivalent I can us开发者_高级运维e when dealing with integers instead of string values?Use String():

When I want to select the nth character, I use the charAt() method, but what's the equivalent I can us开发者_高级运维e when dealing with integers instead of string values?


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;


You could convert the number to a string and do the same thing:

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


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 */
0

精彩评论

暂无评论...
验证码 换一张
取 消