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?
Approach: The idea is to skip (N-1) digits of the given number in base B by dividing the number with B, (N – 1) times and then return the modulo of the current number by the B to get the Nth digit from the right.
To get the second digit of a number:Convert the number to a string. Access the string at index 1 , using square brackets notation e.g. String(num)[1] . Convert the result back to a number to get the second digit of the number.
In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With