Keep leading zero using javascript [duplicate] - javascript

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.

UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"

From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}

function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...

Related

Recursively find the sum of a number's digits w/ RegEx and w/o Eval()

Can anyone suggest an implementation that avoids eval, hopefully uses regex, and executes in 6 lines or less? Its a fun problem.
Input: 12 => 3
Input: 235 => 10 => 1
function baseNumber(n){
var x = eval(n.toString().replace(/(\d)(?=\d)/g, '$1+'))
if(x>9){
return baseNumber(x)
} else {
return x
}
}
If you need to use regex (you could also do the same thing without regex and using split)
function baseNumber(n){
if (n > 9)
return baseNumber(n.toString().match(/(\d)/g).reduce(function(a, b) { return a + Number(b) }, 0))
else
return n;
}
The reduce does the summing up. The match returns the array of matches (i.e. digits)
If you want to handle decimals and negative numbers change the if (n > 9) check to if (n.toString().length > 1)
What about this one:
var input = 235;
while(input > 9) input = String(input).match(/[\d]/g).reduce(function(sum, currentValue) {
return sum + parseInt(currentValue);
}, 0);
console.log(input);
Try casting n to String , utilizing String.prototype.split() , String.prototype.replace() , Array.prototype.splice() , Number() , do.. while loop
function baseNumber(n) {
var x = String(n).replace(/[^\d]/g, "").split(""), y = 0;
do { y += Number(x.splice(0, 1)) } while (!!x.length);
return y > 9 ? baseNumber(y) : y
}
console.log(baseNumber("abc12"), baseNumber("def235"))

Adding Decimal place into number with javascript

I've got this number as a integer 439980
and I'd like to place a decimal place in 2 places from the right. to make it 4399.80
the number of characters can change any time, so i always need it to be 2 decimal places from the right.
how would I go about this?
thanks
function insertDecimal(num) {
return (num / 100).toFixed(2);
}
Just adding that toFixed() will return a string value, so if you need an integer it will require 1 more filter. You can actually just wrap the return value from nnnnnn's function with Number() to get an integer back:
function insertDecimal(num) {
return Number((num / 100).toFixed(2));
}
insertDecimal(99552) //995.52
insertDecimal("501") //5.01
The only issue here is that JS will remove trailing '0's, so 439980 will return 4399.8, rather than 4399.80 as you might hope:
insertDecimal(500); //5
If you're just printing the results then nnnnnn's original version works perfectly!
notes
JavaScript's Number function can result in some very unexpected return values for certain inputs. You can forgo the call to Number and coerce the string value to an integer by using unary operators
return +(num / 100).toFixed(2);
or multiplying by 1 e.g.
return (num / 100).toFixed(2) * 1;
TIL: JavaScript's core math system is kind of weird
Another Method
function makeDecimal(num){
var leftDecimal = num.toString().replace('.', ''),
rightDecimal = '00';
if(leftDecimal.length > 2){
rightDecimal = leftDecimal.slice(-2);
leftDecimal = leftDecimal.slice(0, -2);
}
var n = Number(leftDecimal+'.'+rightDecimal).toFixed(2);
return (n === "NaN") ? num:n
}
makeDecimal(3) // 3.00
makeDecimal(32) // 32.00
makeDecimal(334) // 3.34
makeDecimal(13e+1) // 1.30
Or
function addDecimal(num){
var n = num.toString();
var n = n.split('.');
if(n[1] == undefined){
n[1] = '00';
}
if(n[1].length == 1){
n[1] = n[1]+'0';
}
return n[0]+'.'+n[1];
}
addDecimal(1); // 1.00
addDecimal(11); // 11.00
addDecimal(111); // 111.00
Convert Numbers to money.
function makeMoney(n){
var num = n.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
One More.
function addDecimal(n){
return parseFloat(Math.round(n * 100) / 100).toFixed(2);
}

less than 10 add 0 to number [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 4 years ago.
How can I modify this code to add a 0 before any digits lower than 10
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
c += sec + "″";
return c;
}
So the outpout would change from
4° 7′ 34″W, 168° 1′ 23″N
to
04° 07′ 34″W, 168° 01′ 23″N
Thanks for your time
You can always do
('0' + deg).slice(-2)
See slice():
You can also use negative numbers to select from the end of an array
Hence
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
For ease of access, you could of course extract it to a function, or even extend Number with it:
Number.prototype.pad = function(n) {
return new Array(n).join('0').slice((n || 2) * -1) + this;
}
Which will allow you to write:
c += deg.pad() + '° '; // "04° "
The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:
deg.pad(4) // "0045"
Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).
Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.
Make a function that you can reuse:
function minTwoDigits(n) {
return (n < 10 ? '0' : '') + n;
}
Then use it in each part of the coordinates:
c += minTwoDigits(deg) + "° ";
and so on.
if(myNumber.toString().length < 2)
myNumber= "0"+myNumber;
or:
return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;
You can always do
('0' + deg).slice(-2)
If you use it very often, you may extend the object Number
Number.prototype.pad = function(n) {
if (n==undefined)
n = 2;
return (new Array(n).join('0') + this).slice(-n);
}
deg.pad(4) // "0045"
where you can set any pad size or leave the default 2.
You can write a generic function to do this...
var numberFormat = function(number, width) {
return new Array(+width + 1 - (number + '').length).join('0') + number;
}
jsFiddle.
That way, it's not a problem to deal with any arbitrarily width.
Hope, this help:
Number.prototype.zeroFill= 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;
}
Here is Genaric function for add any number of leading zeros for making any size of numeric string.
function add_zero(your_number, length) {
var num = '' + your_number;
while (num.length < length) {
num = '0' + num;
}
return num;
}
I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.
For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.
This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).
var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
if(deg < 10) deg = '0' + deg;
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
if(min < 10) min = '0' + min;
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
if(sec < 10) sec = '0' + sec;
c += sec + "″";
return c;
}
A single regular expression replace should do it:
var stringWithSmallIntegers = "4° 7′ 34″W, 168° 1′ 23″N";
var paddedString = stringWithSmallIntegers.replace(
/\d+/g,
function pad(digits) {
return digits.length === 1 ? '0' + digits : digits;
});
alert(paddedString);
shows the expected output.

Formatting Number in JavaScript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit
How can I format number to 3 digits like..
9 => 009
99 => 099
100 => 100
This is trivial.
var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;
You can make this into a function easily yourself.
function pad(number, length)
{
var result = number.toString();
var temp = length - result.length;
while(temp > 0)
{
result = '0' + result;
temp--;
}
return result;
}
Surely you need to convert those numbers in strings, because numbers datatype don't "support" initial zeros.
You can toString() the number, then check his length (NUMLENGTH), if it's less than the total number of digits you need (MAXDIGITS) then prepend MAXDIGITS-NUMLENGTH zeros to the string.
http://jsfiddle.net/K3mwV/
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
for (i=1;i <= 100;i++) {
e = i+'';
alert('0'.repeat(3 - e.length)+i);
}
function padZeros(zeros, n) {
// convert number to string
n = n.toString();
// cache length
var len = n.length;
// if length less then required number of zeros
if (len < zeros) {
// Great a new Array of (zeros required - length of string + 1)
// Then join those elements with the '0' character and add it to the string
n = (new Array(zeros - len + 1)).join('0') + n;
}
return n;
}

Format a Number, Exactly Two in Length?

I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:
01
02
03
...
09
10
11
12
...
Update
This answer was written in 2011. See liubiantao's answer for the 2021 version.
Original
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
pad(1); // 01
pad(9); // 09
pad(10); // 10
String("0" + x).slice(-2);
where x is your number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
String(number).padStart(2, '0')
Just use the following short function to get the result you need:
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
A direct way to pad a number to the left in Javascript is to calculate the number of digits by log base 10.
For example:
function padLeft(positiveInteger, totalDigits) {
var padding = "00000000000000";
var rounding = 1.000000000001;
var currentDigits = positiveInteger > 0 ? 1 + Math.floor(rounding * (Math.log(positiveInteger) / Math.LN10)) : 1;
return (padding + positiveInteger).substr(padding.length - (totalDigits - currentDigits));
}
The rounding factor fixes the problem that there is no way to get an exact log of powers of 10, for example Math.log(1000) / Math.LN10 == 2.9999999999999996
Of course one should add validation of the parameters.
// Return a string padded
function FormatMe(n) {
return (n<10) ? '0'+n : n;
}
function leftFillNum(num, targetLength) {
return num.toString().padStart(targetLength, '0');
}
console.log(leftFillNum(3,2)); // ==> returns '03'
console.log(leftFillNum(33,2)); // ==> returns '33'
console.log(leftFillNum(3,4)); // ==> returns '0003'
console.log(leftFillNum(33,5)); // ==> returns '00033'
function padLeft(a, b) {
var l = (a + '').length;
if (l >= b) {
return a + '';
} else {
var arr = [];
for (var i = 0; i < b - l ;i++) {
arr.push('0');
}
arr.push(a);
return arr.join('');
}
}
I usually use this function.
function pad(n, len) {
let l = Math.floor(len)
let sn = '' + n
let snl = sn.length
if(snl >= l) return sn
return '0'.repeat(l - snl) + sn
}
Usage Example
pad(1, 1) // ==> returns '1' (string type)
pad(384, 5) // ==> returns '00384'
pad(384, 4.5)// ==> returns '0384'
pad(5555, 2) // ==> returns '5555'
I use regex to format my time such as
const str = '12:5'
const final = str.replace(/\d+/g, (match, offset, string) => match < 10 ? '0' + match : match)
output: 12:05
Improved version of previous answer:
var result = [...Array(12)].map((_, i) => zeroFill(i + 1, 2));
function zeroFill(num, size) {
let s = num + '';
while (s.length < size) s = `0${s}`;
return s;
}
console.log(result)
lodash has padStart, https://lodash.com/docs/4.17.15#padStart
padStart(1, 2, '0')
it will pad 1 => 01, it wont take care of negative numbers, as - will be considered as padding
const threeDigit = num => num.toString().padStart(3 , '0');
The function converts a number to a string and then returns a three-digit version of the number

Categories

Resources