JavaScript: Get the second digit from a number?

南楼画角 提交于 2019-12-20 10:17:22

问题


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?


回答1:


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;

Demonstration

For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.




回答2:


1st digit of number from right → 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)

Math.floor((1234 / 10) % 10); // 3

3rd digit of number from right → Math.floor((number / 100) % 10)

Math.floor((1234 / 100) % 10); // 2

nth digit of number from right → 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) + 1 Credit to: https://stackoverflow.com/a/28203456/6917157

function getDigitCount(number) {
  return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}

nth digit of number from left or right

function getDigit(number, n, fromLeft) {
  const location = fromLeft ? getDigitCount(number) + 1 - n : n;
  return Math.floor((number / Math.pow(10, location - 1)) % 10);
}



回答3:


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.

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



回答4:


A "number" is one thing.

The representation of that number (e.g. the base-10 string "1234") is another thing.

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?

Q: Why is it so important to not use a string? Is this a homework assignment? An interview question?




回答5:


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.

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.




回答6:


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



回答7:


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>



回答8:


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
        }



回答9:


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



回答10:


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/

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



来源:https://stackoverflow.com/questions/13955738/javascript-get-the-second-digit-from-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!