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 
16
  • 1
    If you put 03 in a variable, it'll just be 3. Commented Nov 23, 2017 at 15:10
  • @LoremIpsum Correct, just dont know how to word it. Commented Nov 23, 2017 at 15:11
  • Your input is already a string Commented Nov 23, 2017 at 15:11
  • 2
    Where is your 03 coming from? If it's being input, it's probably already a string. Commented Nov 23, 2017 at 15:11
  • Use a date or text input instead of number? That lets the user write 03 which will get transmitted to your server as 03 Commented Nov 23, 2017 at 15:12

8 Answers 8

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" 
Sign up to request clarification or add additional context in comments.

Comments

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")); 

3 Comments

But also have to note browser support . None in IE
@charlietfl True that. There's a polyfil on the man page that should help.
Good catch though...never knew it existed
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; } 

Comments

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))

Comments

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); } 

Comments

0

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

mydate=3; mystring = ("0"+3).slice(-2); console.log(mystring);

Comments

0

Try this

 function appendZero(val){ val = val.toString(); return val.length == 1 ? "0"+val : val } appendZero(3) // '03' 

4 Comments

In your return line, there's no need to use .toString(), it's already a string.
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 :)
I meant val is already a string so it should be return val.length == 1 ? "0"+val : val .
Yeah correct.Thanks for pointing out that.Now I understand :)
-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

1 Comment

Thanks for your observation @charlietfl, It made me read the question again so I could come up with a -maybe- helpful answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.