Mohammad Dayyan
Mohammad Dayyan

Reputation: 22408

String.Format in Javascript?

In C# whenever I wanted to print two digit numbers I've used

int digit=1;
Console.Write(digit.ToString("00"));

How can I do the same action in Javascript ?
Thanks

Upvotes: 5

Views: 26611

Answers (4)

KooiInc
KooiInc

Reputation: 122936

c# digit.toString("00") appends one zero to the left of digit (left padding). In javascript I use this functon for that:

function zeroPad(nr,base){
  var  len = (String(base).length - String(nr).length)+1;
  return len > 0? new Array(len).join('0')+nr : nr;
}
zeroPad(1,10);   //=> 01
zeroPad(1,100);  //=> 001
zeroPad(1,1000); //=> 0001

You can also rewrite it as an extention to Number:

Number.prototype.zeroPad = Number.prototype.zeroPad || 
     function(base){
       var nr = this, len = (String(base).length - String(nr).length)+1;
       return len > 0? new Array(len).join('0')+nr : nr;
    };
 //usage:
(1).zeroPad(10);   //=> 01
(1).zeroPad(100);  //=> 001
(1).zeroPad(1000); //=> 0001

[edit oct. 2021]

A static es20xx Number method, also suitable for negative numbers.

Number.padLeft = (nr, len = 2, padChr = `0`) => 
  `${nr < 0 ? `-` : ``}${`${Math.abs(nr)}`.padStart(len, padChr)}`;
console.log(Number.padLeft(3));
console.log(Number.padLeft(284, 5));
console.log(Number.padLeft(-32, 12));
console.log(Number.padLeft(-0)); // Note: -0 is not < 0

Upvotes: 14

DavidMc
DavidMc

Reputation: 21

I usually just do something like ("00000000"+nr).slice(-base) where nr is the number and base is the number of digits you want to end up with.

Upvotes: 2

Anubhav Ranjan
Anubhav Ranjan

Reputation: 1598

var num =10
document.write(num);

But if your question is to use two digit numbers twice then you can use this

var num1 = 10;
var num2 = 20;
var resultStr = string.concat(num1,num2);
document.write(resultStr);
...
Result: 1020

if you want a space in between,

var resultStr = string.concat(num1,"",num2);

Hope this helps...

Upvotes: -1

Hubro
Hubro

Reputation: 59343

One way would be to download sprintf for javascript and writing something like this:

int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"

Upvotes: 1

Related Questions