1

This is a strange one but I need to convert a number to string; a number with zero in front.

3.toString()
String(3)
3 + ""

All those would convert to string, but what about 03? I need 03 to become "03". How to achieve this? Doing the above with 03, I get "3". basically, I am doing queries by date where the value can be "03/15/2017"

From an input's value, I need to convert that exactly to string without dropping the 0 if present.

Here's my example:

<input type="text" value=03 /> // val
dateString = "03/15/2017"
dateString.indexOf(val) !== -1
Sylar
  • 11,422
  • 25
  • 93
  • 166

8 Answers8

3

You are confusing strings and numbers. Numbers have a "canonical form" that you see, for example, when you print or log them; however, numbers can have many different formats that all get parsed or converted into the same number.

For example, consider the following number literals which all represent the same number (3):

[3, 3.0, 03, +3e0].map(Number); // => [3, 3, 3, 3]

Moreover, parsing those literals from string values also results in the same number:

['3', '3.0', '03', '+3e0'].map(Number); // => [3, 3, 3, 3]

What this means is that if you want a number to appear differently than its canonical form then you must "format" it. In your example, it sounds like you're already getting a formatted number ("03") so perhaps you just want to validate the string to confirm that it is an acceptable number and use the input string as-is, or a formatted version of the validated number. For example:

function validateNumber(s) {
  // Parse the input string as a number.
  var n = Number(s);
  // Validate the number to make sure it's ok based on your business logic.
  if (!Number.isInteger(n)) {
    throw new Error('invalid integer: ' + s);
  }
  // Format it to look like we want.
  var formatted = String(s);
  return ((formatted.length < 2) ? '0' : '') + formatted;
}
validateNumber(3); // => "03"
validateNumber("03"); // => "03"
validateNumber(20); // => "20"
maerics
  • 151,642
  • 46
  • 269
  • 291
1

Turns out there's an inbuilt to do this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

console.log("3".padStart(2, "0"));
Simon Brahan
  • 2,016
  • 1
  • 14
  • 22
0

You have a function for return 03 if you use 3, I get this function from this post

console.log(pad(3,2))
function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}
Ramsés Fernández
  • 357
  • 1
  • 3
  • 13
0

Try this

    function appendZero(val){
        val = val.toString();
        return val.length == 1 ? "0"+val : val

    }

    appendZero(3) // '03'
moriah
  • 323
  • 4
  • 16
Shijil Narayanan
  • 1,011
  • 8
  • 21
  • In your return line, there's no need to use `.toString()`, it's already a string. – cнŝdk Nov 23 '17 at 15:17
  • Yes,but just a check incase the value passed in is a number.If the datatype of value passed is a number then the result returned will be '3' instead of '03'.Hence inorder to handle that,I thought of stringifying it :) – Shijil Narayanan Nov 23 '17 at 15:26
  • I meant `val` is already a `string` so it should be `return val.length == 1 ? "0"+val : val` . – cнŝdk Nov 23 '17 at 15:29
  • 1
    Yeah correct.Thanks for pointing out that.Now I understand :) – Shijil Narayanan Nov 24 '17 at 06:39
0

you can get with an if condition to check if the number is less than 10.

function addZero(n) {
return (n < 10) ? ("0" + n) : n.toString();
}
console.log(addZero(7))

moriah
  • 323
  • 4
  • 16
Gamsh
  • 545
  • 4
  • 21
0

Considering your example this may work for you:

var val = 3;
dateString = "03/15/2017";
var indexOfVal = dateString.indexOf(val.toString().padStart(2,'0'));
console.log(indexOfVal); // 0

//Another approach could be
var datePartsArray = dateString.split("/");
var month = datePartsArray[0]; //"03"
var day = datePartsArray[1]; //"15"
var year = datePartsArray[2]; //"2017"

if(month===val.toString().padStart(2,'0')){
   console.log(true);}
else{
    console.log(false);
    }
Emilio Lucas Ceroleni
  • 1,559
  • 2
  • 9
  • 13
0

This is also a short one I usually use for concatenating date-strings:

mydate=3;
mystring = ("0"+3).slice(-2);
console.log(mystring);
zuluk
  • 1,557
  • 8
  • 29
  • 49
-3

Maybe this helps:

var today = new Date();
var d = today.getDate();
var m = today.getMonth() + 1;
var y = today.getFullYear();
var shortDate = m.toString().padStart(2,'0') + '/' + 
d.toString().padStart(2,'0') + '/' + y.toString();
console.log(shortDate);

In the third line I add 1 to today.getMonth() because JavaScript counts months from 0 to 11 in a year.

You can find more about JavaScript Date Methods here

Emilio Lucas Ceroleni
  • 1,559
  • 2
  • 9
  • 13