0

How can I convert a string to number without loosing the trailing zeroes

var string1 = '02';
Number(string1); // == 2 - Default output
Number(string1); // == 02 - My requirement

The reason why I want this is: I am passing a date as value to the date HTML element. And the format is yyyy-MM-dd, month and date format is two digits and if I convert the date (string in my case) to number the leading zeroes are being removed.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Sarath Raja
  • 97
  • 1
  • 1
  • 11
  • You cannot. You will have to parse as number and then again convert it to string with `0`s. A simple approach is `("00" + number).slice(-2)` – Rajesh Feb 01 '17 at 09:04
  • @Rajesh I am trying to do . Is there a way to do that. – Sarath Raja Feb 01 '17 at 09:06
  • @Rajesh How does slice(-2) is going to work? – Sarath Raja Feb 01 '17 at 09:14
  • It will return last 2 characters in string. https://jsfiddle.net/RajeshDixit/3jr4qy6o/ – Rajesh Feb 01 '17 at 09:15
  • Possible Duplicate: http://stackoverflow.com/questions/8043026/javascript-format-number-to-have-2-digit. Note, not marking it dupe as OP wants to deal with `input type="date"` – Rajesh Feb 01 '17 at 09:23

2 Answers2

2

You can't. A Number is a Number, period. You can make a helper object to have a number and a number leftpad method at your disposal. Something like:

document.querySelector("button").addEventListener("click", setDateValueExample);
var num = XNumber(3);
var result = {
  el: document.querySelector("#result"),
  log(str) {
    this.el.textContent += str + '\n';
  }
}
// XNumber usage example
result.log('XNumber(54).lpad(1000000): ' + XNumber(54).lpad(1000000));

// Datefield value from date field formatting example
var d = new Date(document.querySelector("#somedate").value);
result.log('Date formatted: ' +
  [XNumber(d.getMonth()+1).lpad(),
   XNumber(d.getDate()).lpad(),
   d.getFullYear()].join('-'));

// Set date field value from string example
function setDateValueExample() {
  document.querySelector("#somedate").value =
    document.querySelector("button").getAttribute("data-dateString")
      .split("/")
      .reverse()
      .map(function (v) {
        return XNumber(v).lpad()
      })
      .join('-');
}

// The actual Number helper
function XNumber(num) {
  return {
    num: +num,
    lpad (base) {
      base = base || 10;
      var  len = (String(base).length - String(this.num).length)+1;
      return len > 0 ? new Array(len).join('0')+this.num : this.num;
    }
  };
}
<input type="date" id="somedate" value="2017-02-01"/> a date
<button data-dateString="2/3/2017">Set value from string "2/3/2017"</button>
<pre id="result"></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Just a pointer, OP is looking for applying it on `input type="date"`. If question is just about getting double digit number, then I have already shared a dupe link and we should close it as dupe. – Rajesh Feb 01 '17 at 09:28
  • Added a demo date field – KooiInc Feb 01 '17 at 09:39
1

As commented, you can use ("00" + num).slice(-2).

You can try something like this:

function getParsedValue(date) {
  var d = date;
  if (typeof d === "string") {
    d = new Date(date);
  }
  return [d.getFullYear(), getDoubleDigitString(d.getMonth() + 1), getDoubleDigitString(d.getDate())].join("-")
}

function getDoubleDigitString(num) {
  return ("00" + num).slice(-2);
}

var date = new Date();
document.getElementById('txtDate1').value = getParsedValue(date)

document.getElementById('txtDate2').value = getParsedValue("1999/1/2")
<input type="date" id="txtDate1" />
<input type="date" id="txtDate2" />
Rajesh
  • 24,354
  • 5
  • 48
  • 79