Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra zeros in front of a number using jQuery?

Tags:

javascript

I have file that are uploaded which are formatted like so

MR 1

MR 2

MR 100

MR 200

MR 300

ETC.

What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99

So files are formatted

MR 001

MR 010

MR 076

ETC.

Any help would be great!

like image 662
Chill Web Designs Avatar asked Jun 24 '11 09:06

Chill Web Designs


People also ask

What is number in jQuery?

jQuery isNumeric() methodThe isNumeric() method in jQuery is used to determine whether the passed argument is a numeric value or not. The isNumeric() method returns a Boolean value. If the given argument is a numeric value, the method returns true; otherwise, it returns false.


2 Answers

Assuming you have those values stored in some strings, try this:

function pad (str, max) {   str = str.toString();   return str.length < max ? pad("0" + str, max) : str; }  pad("3", 3);    // => "003" pad("123", 3);  // => "123" pad("1234", 3); // => "1234"  var test = "MR 2"; var parts = test.split(" "); parts[1] = pad(parts[1], 3); parts.join(" "); // => "MR 002" 
like image 145
Todd Yandell Avatar answered Oct 15 '22 08:10

Todd Yandell


I have a potential solution which I guess is relevent, I posted about it here:

https://www.facebook.com/antimatterstudios/posts/10150752380719364

basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code

var d = new Date(); var h = ("0"+d.getHours()).slice(-2); var m = ("0"+d.getMinutes()).slice(-2); var s = ("0"+d.getSeconds()).slice(-2); 

I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.

then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.

like image 31
Christopher Thomas Avatar answered Oct 15 '22 09:10

Christopher Thomas