Remove decimal zeros based on maximum consecutive zeros

I have a page with a grid where user numbers are saved. It has the following pattern: each number ends with 3 digits after the decimal point. It doesn’t look very good when, for example, user input

123,450
123,670
123,890

It is much better to have only 2 decimal places, because the latter is 0completely meaningless and superfluous.

Until now, it should have 3 digits only if at least one element in the array does not end 0

For instance:

123,455
123,450
123,560

In this case, the 1st element of the array has the last digit that is not equal 0, and therefore, all elements must have 3 digits. The same story with 2 or 1 zeros

Zeros are redundant:

123,30
123,40
123,50

Need zeros:

123,35
123,40
123,50

The question is, how can I implement it programmatically? I started like this:

var zeros2Remove = 0;
numInArray.forEach(function(item, index, numInArray) 
{
    var threeDigitsAfterComma = item.substring(item.indexOf(',') + 1);

    for(var j = 2; j <= 0; j--) 
    {
        if(threeDigitsAfterComma[j] == 0) 
        {
            zeros2Remove =+ 1;
        } 
        else //have no idea what to do..
    }   
})

, , , , , 1 , . , , , ...

+4
5

, , , , :

var arr = ["111.3030", "2232.0022", "3.001000", "4","558.0200","55.00003000000"];
var map = arr.map(function(a) {
  if (a % 1 === 0) {
    var res = "1";
  } else {
    var lastNumman = a.toString().split('').pop();
    if (lastNumman == 0) {
      var m = parseFloat(a);
      var res = (m + "").split(".")[1].length;
    } else {
      var m = a.split(".")[1].length;
      var res = m;
    }
  }

  return res;

})
var maxNum = map.reduce(function(a, b) {
  return Math.max(a, b);
});

arr.forEach(function(el) {
  console.log(Number.parseFloat(el).toFixed(maxNum));
});
Hide result
+2

, . , / .

, .

// Define any array
const firstArray = [
  '123,4350',
  '123,64470',
  '123,8112390',
]

const oneOfOfYourArrays = [
  '123,30',
  '123,40',
  '123,50',
]

// Converts 123,45 to 123.45
function stringNumberToFloat(stringNumber) {
  return parseFloat(stringNumber.replace(',', '.'))
}

// For 123.45 you get 2
function getNumberOfDecimals(number) {
  return number.split('.')[1].length;
}

// This is a hacky way how to remove traling zeros
function removeTralingZeros(stringNumber) {
  return stringNumberToFloat(stringNumber).toString()
}

// Sorts numbers in array by number of their decimals
function byNumberOfValidDecimals(a, b) {
  const decimalsA = getNumberOfDecimals(a)
  const decimalsB = getNumberOfDecimals(b)
  return decimalsB - decimalsA
}

// THIS IS THE FINAL SOLUTION
function normalizeDecimalPlaces(targetArray) {
  const processedArray = targetArray
  .map(removeTralingZeros) // We want to remove trailing zeros
  .sort(byNumberOfValidDecimals) // Sort from highest to lowest by number of valid decimals

  const maxNumberOfDecimals = processedArray[0].split('.')[1].length

  return targetArray.map((stringNumber) => stringNumberToFloat(stringNumber).toFixed(maxNumberOfDecimals))
}

console.log('normalizedFirstArray', normalizeDecimalPlaces(firstArray))

console.log('normalizedOneOfOfYourArrays', normalizeDecimalPlaces(oneOfOfYourArrays))
Hide result
+1

MDN,

forEach(), . , forEach() . for...of.

forEach for, break:

// unrelated example
let i;
let j;
outerLoop:
for (i = 2; i < 100; ++i) {
  innerLoop:
  for (j = 2; j < 100; ++j) {
    // brute-force prime factorization
    if (i * j === 2183) { break outerLoop; }
  }
}
console.log(i, j);
Hide result

, . :

function getTrailingZeroes (str) {
  return str.match(/0{0,2}$/)[0].length;
}

str.match(/0{0,2}$/) 0 2 str . - , str. , , Array.map :

function getShortenedNumbers (numInArray) {
  let zeroesToRemove = Infinity;
  for (const str of numInArray) {
    let candidate = getTrailingZeroes(str);
    zeroesToRemove = Math.min(zeroesToRemove, candidate);
    if (zeroesToRemove === 0) break;
  }

  return numInArray.map(str => str.substring(0, str.length - zeroesToRemove);
}

:

function getTrailingZeroes (str) {
  return str.match(/0{0,2}$/)[0].length;
}

function getShortenedNumbers (numInArray) {
  let zeroesToRemove = Infinity;
  for (const str of numInArray) {
    let candidate = getTrailingZeroes(str);
    zeroesToRemove = Math.min(zeroesToRemove, candidate);
    if (zeroesToRemove === 0) break;
  }

  return numInArray.map(str => str.substring(0, str.length - zeroesToRemove));
}

console.log(getShortenedNumbers(['123,450', '123,670', '123,890']));
console.log(getShortenedNumbers(['123,455', '123,450', '123,560']));
Hide result
+1

function removeZeros(group) {
    var maxLength = 0;
  var newGroup = [];
    for(var x in group) {
    var str = group[x].toString().split('.')[1];
    if(str.length > maxLength) maxLength = str.length;
  }

  for(var y in group) {
    var str = group[y].toString();
    var substr = str.split('.')[1];
    if(substr.length < maxLength) {
        for(var i = 0; i < (maxLength - substr.length); i++) 
        str += '0';
    } 
    newGroup.push(str); 
  }

  return newGroup;
}

jsfiddle: https://jsfiddle.net/32sdvzn1/1/

My script , , JavaScript , 3.10 3.1, , , .

Update

I updated the script, the new version adds as many zeros as it differs from the maximum decimal length and decimal length of the analyzed number.

Example

We have: 3.11, 3.1423, 3.1

Maximum Length: 4 (1423)

maxLenght (4) - length .11 (2) = 2

We will add 2 zeros in 3.11, which will be 3.1100

+1
source

I think you can start by assuming that you remove two extra zeros and skip your array by looking for numbers in the last two places. With commas, I assume that your numArray elements are strings, all starting at the same length.

var numArray = ['123,000', '456,100', '789,110'];

var removeTwo = true, removeOne = true;
for (var i = 0; i < numArray.length; i++) {
    if (numArray[i][6] !== '0') { removeTwo = false; removeOne = false; }
    if (numArray[i][5] !== '0') { removeTwo = false; }
}

// now loop to do the actual removal
for (var i = 0; i < numArray.length; i++) {
    if (removeTwo) {
        numArray[i] = numArray[i].substr(0, 5);
    } else if (removeOne) {
        numArray[i] = numArray[i].substr(0, 6);
    }
}
0
source

Source: https://habr.com/ru/post/1693028/


All Articles