[Solved] How to remove price zeros? [closed]


The issue with your code is the condition, it processes all digits in reverse until the first non-zero character, without limit. You could keep a loop counter and not iterate more than 6 times; a for-loop with appropriate exit condition would work here. Though you don’t need to make it this complicated.

Two simple methods:

  1. Integer division: divide by 1000000 to remove the last 6 digits.
console.log(Math.floor(800000000 / 1000000)) // 800
console.log(Math.floor(699000000 / 1000000)) // 699
  1. String slice: copy all but the last 6 characters.
console.log("800000000".slice(0, -6)) // 800
console.log("699000000".slice(0, -6)) // 699

If you need a more general/unopinionated solution, use a for-loop to check each character from the end for non-zero-ness, and slice that amount, up to 6|max from the string and return.

const removeUpTo6Zeros = val => {
  let i;
  for (i = 0; i < 6; i++) {
    if (val[val.length - 1 - i] !== '0') break;
  }
  return i ? val.slice(0, -i) : val;
};

console.log(removeUpTo6Zeros("800000000")); // 800
console.log(removeUpTo6Zeros("699000000")); // 699
console.log(removeUpTo6Zeros("699000030")); // 69900003
console.log(removeUpTo6Zeros("699001003")); // 699001003
console.log(removeUpTo6Zeros("69900"));     // 699
console.log(removeUpTo6Zeros("69"));        // 69
console.log(removeUpTo6Zeros("6"));         // 6
console.log(removeUpTo6Zeros("0"));         // ""
console.log(removeUpTo6Zeros("00"));        // ""
console.log(removeUpTo6Zeros("000"));       // ""

solved How to remove price zeros? [closed]