How to remove 0 from sting nominal, but not remove form decimal in javascript

Viewed 56

I have case to remove 0 from string number, but case in decimal 0 not will remove. what logic to remove that? in javascript. example:

01.00 -> 1.00 
0.50 -> 0.50 (not .50)
010.05 -> 10.05
3 Answers

We can try replacing on the pattern ^0+(?=\d), which will target only leading zeroes which in turn are followed by at least one other digit.

var input = ["01.00", "0.50", "010.05"];
for (var i=0; i < input.length; ++i) {
    var output = input[i].replace(/^0+(?=\d)/, "");
    console.log(input + " => " + output);
}

One solution would be to remove all of the left-most zeros. If you're left with a leading dot, then add one zero back in.

function formatNumb(numStr) {
  const result = numStr.replace(/^0+/, '')
  return result[0] === '.' ? '0' + result : result
}

console.log(formatNumb('01.00')) // 1.00 
console.log(formatNumb('0.50')) // 0.50 (not .50)
console.log(formatNumb('010.05')) // 10.05

Another solution that doesn't involve Regex: Split on ".", convert the left to a number (which automatically strips zeros, but leaves at least one zero), then recombine the parts.

function formatNumb(numStr) {
  const [left, right] = numStr.split('.')
  return Number(left) + '.' + right
}

console.log(formatNumb('01.00')) // 1.00 
console.log(formatNumb('0.50')) // 0.50 (not .50)
console.log(formatNumb('010.05')) // 10.05

This could be also achieved without regEx if the fraction is fixed (or can be evaluated in advance)

  e.g.  (+"0.50").toFixed(2)

var sequence = ["01.00", "0.50", "010.05"];

sequence
  .map(item=> `${item} => ${(+item).toFixed(2)}`)
  .forEach(item=> console.log(item))

Related