Pier Stein
Pier Stein

Reputation: 49

How to use NumberFormat in Javascript?

I'd like my countdown timer to show double digits, like "53:00" instead of "53:0". Not sure what's going wrong here? Thank you!

function convertSeconds(s) {
    var min = Math.floor(s / 60);
    var sec = s % 60;
    return nf(min, 2) + ':' + nf(sec, 2);
  }

Upvotes: 2

Views: 349

Answers (4)

Adnan Toky
Adnan Toky

Reputation: 1943

The nf() function should be like this:

function nf(num){
    if(num < 10){
        return "0"+num;
    }
    return num;
}

console.log(nf(7));
// 07
console.log(nf(11));
// 11

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

If by nf() you mean a function that formats a Number as string of given digits, this can be an implementation of it:

function nf(number, digits) {
  var res = number.toString();
  while (res.length < digits) {
    res = "0" + res;
  }
  return res;
}

Demo:

function convertSeconds(s) {
  var min = Math.floor(s / 60);
  var sec = s % 60;
  return nf(min, 2) + ':' + nf(sec, 2);
}

function nf(number, digits) {
  var res = number.toString();
  while (res.length < digits) {
    res = "0" + res;
  }
  return res;
}

console.log(nf(4,2));

Upvotes: 1

inorganik
inorganik

Reputation: 25525

To pad zeroes you can do

function nf(num, places) {
  var s = '0' + num;
  return s.slice(places * -1);
}

function convertSeconds(s) {
  var min = Math.floor(s / 60);
  var sec = s % 60;
  return nf(min, 2) + ':' + nf(sec, 2);
}

Should get you what you want

Upvotes: 2

Mark
Mark

Reputation: 92440

You can use padStart() to make sure a string is a certain length. If it's not it will pad it with whatever you want. In this case 0:

const nf = (n, c) => n.toString().padStart(c, '0');

function convertSeconds(s) {
  var min = Math.floor(s / 60);
  var sec = (s % 60)
  return nf(min, 2) + ':' + nf(sec, 2);
}

console.log(convertSeconds(64))
console.log(convertSeconds(119))

Not sure if you want to pad the minutes of not.

There is also the Intl.NumberFormat() which has an option for minimum digits (though this seems like overkill for this):

console.log(new Intl.NumberFormat('en-US', { minimumIntegerDigits: 2}).format(2));

console.log(new Intl.NumberFormat('en-US', { minimumIntegerDigits: 2}).format(59));

Upvotes: 2

Related Questions