Adding extra zeros in front of a number using jQuery? - 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!

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"

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.

Note: see Update 2 if you are using latest ECMAScript...
Here a solution I liked for its simplicity from an answer to a similar question:
var n = 123
String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5); // returns 00123
UPDATE
As #RWC suggested you can wrap this of course nicely in a generic function like this:
function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}
leftPad(123, 5); // returns 00123
And for those who don't like the slice:
function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}
But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.
UPDATE 2
In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.
So with ES6 it became as simple as:
var n = '123';
n.padStart(5, '0'); // returns 00123
Note: #Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error.
So in case the variable is or could be a number you should cast it to a string first:
String(n).padStart(5, '0');

function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
//addLeadingZeros (1, 3) = "001"
//addLeadingZeros (12, 3) = "012"
//addLeadingZeros (123, 3) = "123"

This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023

If you split on the space, you can add leading zeros using a simple function like:
function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}
So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.
Or as a regular expression:
function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}
I'm sure someone can do it with one replace, not two.
Edit - examples
alert(addZeros('MR 3')); // MR 003
alert(addZeros('MR 23')); // MR 023
alert(addZeros('MR 123')); // MR 123
alert(addZeros('foo bar 23')); // foo bar 023
It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.

Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)
function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.

var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me !
To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits

In simple terms we can written as follows,
for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;
//Because most of the time we need this for day, month or amount matters.

Know this is an old post, but here's another short, effective way:
edit: dur. if num isn't string, you'd add:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful

Related

Undefined in Split String

i have a function to split string into 2 part, front and back. Then reverse it to back and front. Here is my code
function reverseString(string) {
let splitString = ""
let firstString = ""
for(i = 0; i <= string.length/2 - 1; i++) {
firstString += string[i]
}
for(i = string.length/2; i <= string.length; i++) {
splitString += string[i]
}
return splitString + firstString
}
Sorry for bad explanation, this is test case and expected result (first one is expected result, the second one is my result)
console.log(reverseString("aaabccc")); // "cccbaaa" "undefinedundefinedundefinedundefinedaaa"
console.log(reverseString("aab")); // "baa" "undefinedundefineda"
console.log(reverseString("aaaacccc")); // "ccccaaaa" "ccccundefinedaaa"
console.log(reverseString("abcdefghabcdef")); // "habcdefabcdefg" "habcdefundefinedabcdefg"
could you help me, whats wrong with it. Thank you
You could try another approach and use the slice function
function reverseString(string)
{
if (string.length < 2) { return string; }
let stringHalfLength = string.length / 2;
let isLengthOdd = stringHalfLength % 1 !== 0;
if (isLengthOdd) {
return string.slice(Math.ceil(stringHalfLength), string.length + 1) + string[Math.floor(stringHalfLength)] + string.slice(0, Math.floor(stringHalfLength));
}
return string.slice(stringHalfLength, string.length + 1) + string.slice(0, stringHalfLength);
}
console.log(reverseString("aaabccc") === "cccbaaa");
console.log(reverseString("aab") === "baa");
console.log(reverseString("aaaacccc") === "ccccaaaa");
console.log(reverseString("abcdefghabcdef") === "habcdefabcdefg");
A more efficient way to reverse the string would be to split the string, then use the built-in reverse javascript function (which reverses the elements of the split string), and then re-join the elements using the join function.. No need to re-invent the wheel?
You can concatenate the functions in shorthand (.split.reverse.join etc...) so your function would look something like this:
function reverseString(string) {
return string.split("").reverse().join("");
}
Try it out!
function reverseString(string) {
return string.split("").reverse().join("");
}
console.log(reverseString("hello"));
console.log(reverseString("aaabbbccc"));
If there's a particular reason you're opting not to use the in-built functions (i.e. if I've missed something?) , feel free to comment.
The short version of what you need:
function reverseString(string) {
const splitPosition = Math.ceil(string.length / 2);
return string.substring(splitPosition) + string.substring(0, splitPosition);
}
The key to your question is the middle element. To accomplish that, you probably want to use Math.floor that round under.
console.log(reverseString("aaabccc")); // "cccbaaa"
console.log(reverseString("abcdefghabcdef")); // "habcdefabcdefg"
function reverseString (str) {
if (str.length<2) {
return str
}
var half = Math.floor(str.length / 2);
return (str.slice(-half) + (str.length%2?str[half]:"") + str.slice(0,half));
}
reverseString('')
> ""
reverseString('1')
> "1"
reverseString('12')
> "21"
reverseString('123')
> "321"
reverseString('1234')
> "3412"
reverseString('12345')
> "45312"
reverseString("aaabccc")
> "cccbaaa"
reverseString("abcdefghabcdef")
> "habcdefabcdefg"
So basically your problem is not to grab 2 parts of the string and rearrange, it is to grab 3 parts.
1 part: str.slice(0,half)
2 part: str.length%2 ? str[half] : ""
3 part: str.slice(-half)
The second part is empty if the string length is even and the middle character if is odd.
So the code version in long self explanatory code:
function reverseString (str) {
if (str.length<2) {
return str
}
var half = Math.floor(str.length / 2);
var firstPart = str.slice(0,half);
var midlePart = str.length % 2 ? str[half] : ""; // we could expand also this
var endPart = str.slice(-half);
return endPart + midlePart + firstPart;
}
And also, notice the precondition, so I don't have to deal with the easy cases.
Also, in your code, you got undefined because you access in the last loop to:
string[string.length] you need to change <= by <

Function that pads with zeros an input number

i'm having a serious issue here. I have a function that pads a user's input with zeros. For example if i enter 88 it will normalize it to:
00000088. My function is this:
export default length => (value) => {
const noLeadingZeros = value.toString().replace(/(0+)/, '');
if (noLeadingZeros.length === 0) {
return value;
}
return padLeft(noLeadingZeros, length);
};
with padleft is:
export default (num, len) => (
len > num.toString().length ? '0'.repeat(len - num.toString().length) + num
: num
);
My problem is that if i entered something like this:
80112345 it convert it to 08112345. Any ideas?
Using slice:
let str = '00000000' + 88;
let resp = str.slice(-8, str.length)
console.log(resp) // 00000088
In your replace, you're replacing all the zeros in the number not just those on the left side, and even if there are zeros on the left side, why remove them if you're just going to add them back. You could use a for loop that pads the string with a zero n times (where n is the number of digits that the string needs to have length 8), or (thanks to a comment by #AndrewBone), you can use the .repeat() function that does this for you:
function padLeft(value, len) {
return '0'.repeat(String(value).length < len ? len - String(value).length : 0) + value;
}
console.log(padLeft("", 8));
console.log(padLeft("88", 8));
console.log(padLeft("00088", 8));
console.log(padLeft("12312388", 8));
console.log(padLeft("00000000", 8));
this looks wrong :
const noLeadingZeros = value.toString().replace(/(0+)/, '');
you are deleting every zeros out of your number... even those inside !
You can use this regex instead, instead of for /(0+)/ in your code :
/\b(0+)/
explanation : the \b ensures the zeros are at the beginning of a word
or this
/^(0+)/
explanation : the ^ ensure this is the beginning of the string
Just use a RegEx to assert that the number is a valid number.
/0+/
Then get the number of digits in the number:
('' + num).length;
Then put the whole thing together
var paddedNum ='';
for (var i=0;i<8-len;i++) {
paddedNum += "0";
}
paddedNum += num;

Numbers in the form of 001

Is there a special name for numbers in the format of 001.
For example the number 20 would be 020 and 1 would be 001. Its hard to Google around when you don`t know somethings name! Since I am already wasting your guys time does any one know a function for changing numbers to this format.
I think this is usually called "padding" the number.
Its called left zero padded numbers.
It's called padding.
Well, if you're talking about that notation within the context of certain programming languages, 020 as opposed to 20 would be Octal rather than Decimal.
Otherwise, you're referring to padding.
A quick google search revealed this nice snippet of code for Number Padding:
http://sujithcjose.blogspot.com/2007/10/zero-padding-in-java-script-to-add.html
function zeroPad(num,count)
{
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
You can use a simple function like:
function addZ(n) {
return (n<10? '00' : n<100? '0' : '') + n;
}
Or a more robust function that pads the left hand side with as many of whatever character you like, e.g.
function padLeft(n, c, len) {
var x = ('' + n).length;
x = (x < ++len)? new Array(len - x) : [];
return x.join(c) + n
}
Try this one:
Number.prototype.toMinLengthString = function (n) {
var isNegative = this < 0;
var number = isNegative ? -1 * this : this;
for (var i = number.toString().length; i < n; i++) {
number = '0' + number;
}
return (isNegative ? '-' : '') + number;
}

How can I parse a string in Javascript?

I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.

JQuery/JavaScript increment number

I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);

Categories

Resources