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.

5
  • You cannot. You will have to parse as number and then again convert it to string with 0s. A simple approach is ("00" + number).slice(-2) Commented Feb 1, 2017 at 9:04
  • @Rajesh I am trying to do <input type = "date" value = variableName>. Is there a way to do that. Commented Feb 1, 2017 at 9:06
  • @Rajesh How does slice(-2) is going to work? Commented Feb 1, 2017 at 9:14
  • It will return last 2 characters in string. jsfiddle.net/RajeshDixit/3jr4qy6o Commented Feb 1, 2017 at 9:15
  • Possible Duplicate: stackoverflow.com/questions/8043026/…. Note, not marking it dupe as OP wants to deal with input type="date" Commented Feb 1, 2017 at 9:23

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Added a demo date field
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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.