Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function findNthDigit(arr) that accepts as a parameter an array of two numbers
- num and n and returns the n-th digit of given decimal number num counted from right to left.
- Return undefined when the number does not have n-th digit. Write a JS program nthDigitOfNumber.js
- that invokes your function with the sample input data below and prints the output at the console. */
- "use strict";
- function findNthDigit(arr) {
- var n;
- if (arr[0] % 1 === 0) n = parseInt(arr[0]);
- var num = parseFloat(arr[1]);
- if (n == undefined || num !== Number(num) || !n) {
- return undefined + ' - Wrong Input arguments!!!';
- }
- num = Math.abs(num);
- while (num % 1 != 0) {
- num *= 10;
- }
- var numStr = num.toString(10);
- if (n > numStr.length) {
- return undefined + ' - The number doesnβt have ' + n + ' digits!';
- }
- return numStr.charAt(numStr.length - n);
- }
- console.log(findNthDigit([1, 6]));
- console.log(findNthDigit([2, -55]));
- console.log(findNthDigit([6, 923456]));
- console.log(findNthDigit([3, 1451.78]));
- console.log(findNthDigit([6, 888.88]));
- console.log(findNthDigit([0, 321]));
- console.log(findNthDigit(['2', '258.12']));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement