Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a number by a decimal

I'm trying to transform an array of numbers such that each number has only one nonzero digit. so basically

"7970521.5544"

will give me

 ["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]

I tried:

  var j = "7970521.5544"

  var k =j.replace('.','')

  var result = k.split('')

  for (var i = 0; i < result.length; i++) {
  console.log(parseFloat(Math.round(result[i] * 10000) /10).toFixed(10))
}

Any ideas, I'm not sure where to go from here?

like image 692
ronoc4 Avatar asked Dec 05 '18 16:12

ronoc4


2 Answers

Algorithm:

  • Split the number in two parts using the decimal notation.

  • Run a for loop to multiply each digit with the corresponding power of 10, like:
    value = value * Math.pow(10, index); // for digits before decimal
    value = value * Math.pow(10, -1 * index); // for digits after decimal
    

  • Then, filter the non-zero elements and concatenate both the arrays. (remember to re-reverse the left-side array)

    var n = "7970521.5544"
    
    var arr = n.split('.'); // '7970521' and '5544'
    var left = arr[0].split('').reverse(); // '1250797'
    var right = arr[1].split(''); // '5544'
    
    for(let i = 0; i < left.length; i++)
      left[i] = (+left[i] * Math.pow(10, i) || '').toString();
    
    for(let i = 0; i < right.length; i++) 
      right[i] = '.' + +right[i] * Math.pow(10, -i);
    
    let res = left.reverse() // reverses the array
      .filter(n => !!n) 
    // ^^^^^^ filters those value which are non zero
      .concat(right.filter(n => n !== '.0'));
    // ^^^^^^ concatenation
      
    console.log(res);
  • like image 130
    vrintle Avatar answered Sep 28 '22 23:09

    vrintle


    You can use padStart and padEnd combined with reduce() to build the array. The amount you want to pad will be the index of the decimal minus the index in the loop for items left of the decimal and the opposite on the right.

    Using reduce() you can make a new array with the padded strings taking care to avoid the zeroes and the decimal itself.

    let s = "7970521.5544"
    let arr = s.split('')
    let d_index = s.indexOf('.')
    if (d_index == -1) d_index = s.length  // edge case for nums with no decimal
    
    let nums = arr.reduce((arr, n, i) => {
      if (n == 0 || i == d_index) return arr
      arr.push((i < d_index) 
          ? n.padEnd(d_index - i, '0')
          : '.' + n.padStart(i - d_index, '0'))
      return arr
    }, [])
    
    console.log(nums)
    like image 44
    Mark Avatar answered Sep 28 '22 23:09

    Mark