Advertisement
dimipan80

N-th Digit of Number

Nov 15th, 2014
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function findNthDigit(arr) that accepts as a parameter an array of two numbers
  2. num and n and returns the n-th digit of given decimal number num counted from right to left.
  3. Return undefined when the number does not have n-th digit. Write a JS program nthDigitOfNumber.js
  4. that invokes your function with the sample input data below and prints the output at the console. */
  5.  
  6. "use strict";
  7.  
  8. function findNthDigit(arr) {
  9.     var n;
  10.     if (arr[0] % 1 === 0) n = parseInt(arr[0]);
  11.  
  12.     var num = parseFloat(arr[1]);
  13.     if (n == undefined || num !== Number(num) || !n) {
  14.         return undefined + ' - Wrong Input arguments!!!';
  15.     }
  16.  
  17.     num = Math.abs(num);
  18.     while (num % 1 != 0) {
  19.         num *= 10;
  20.     }
  21.  
  22.     var numStr = num.toString(10);
  23.     if (n > numStr.length) {
  24.         return undefined + ' - The number doesn’t have ' + n + ' digits!';
  25.     }
  26.  
  27.     return numStr.charAt(numStr.length - n);
  28. }
  29.  
  30. console.log(findNthDigit([1, 6]));
  31. console.log(findNthDigit([2, -55]));
  32. console.log(findNthDigit([6, 923456]));
  33. console.log(findNthDigit([3, 1451.78]));
  34. console.log(findNthDigit([6, 888.88]));
  35. console.log(findNthDigit([0, 321]));
  36. console.log(findNthDigit(['2', '258.12']));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement