Skip to content Skip to sidebar Skip to footer

Removing Zeros After Comma Based On Maximum Consequent Zeros

I have a page with a grid where user's numbers get saved. It has a following pattern - every number ends with 3 digits after comma. It doesn't look nice, when for example user's in

Solution 1:

I think the following code what you are looking for exactly , please manipulate numbers and see the changes :

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));
});

Solution 2:

According to MDN,

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop or for...of instead.

If you convert your forEach loop to a for loop, you can break out of it with a label and break statement:

// 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);

I gave you an unrelated example because your problem doesn't need nested loops at all. You can find the number of trailing zeroes in a string with a regular expression:

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

str.match(/0{0,2}$/) finds between 0 and 2 zeroes at the end of str and returns them as a string in a one-element array. The length of that string is the number of characters you can remove from str. You can make one pass over your array of number-strings, breaking out when necessary, and use Array.map as a separate truncation loop:

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);
}

All together:

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']));

Solution 3:

This solution might seem a little cumbersome but it should work for all possible scenarios. It should be easy enough to make always return a minimal number of decimals places/leading zeros.

I hope it helps.

// 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))

Solution 4:

Try this

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;
}

Try it on jsfiddle: https://jsfiddle.net/32sdvzn1/1/

My script checks the length of every number decimal part, remember that JavaScript removes the last zeros in a decimal number, so 3.10 would be 3.1, so the length is less when there is a number with zeros in the end, in this case we just add a zero to the number.

Update

I've updated the script, the new version adds as much zeros as the different between the max decimal length and the decimal length of the analyzed number.

Example

We have: 3.11, 3.1423, 3.1

The max length would be: 4 (1423)

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

We add 2 zeros to 3.11, that will become 3.1100


Solution 5:

I think you can start out assuming you will remove two extra zeros, and loop through your array looking for digits in the last two places. With the commas, I'm assuming your numArray elements are strings, all starting with 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);
    }
}

Post a Comment for "Removing Zeros After Comma Based On Maximum Consequent Zeros"