0

I would like to format my numbers with leading zeros when needed:

Example:

1 >> 01

5 >> 05

10 >> 10

I've tried this:

<td data-bind="text: ProjectId.toString('00')"></td>

Where ProjectId is the property containing my number.

But it doesn't work. I get the error Number.prototype.toString: invalid argument

Any idea?

nemesv
  • 138,284
  • 16
  • 416
  • 359
Bronzato
  • 9,438
  • 29
  • 120
  • 212

2 Answers2

0

For very simple cases this should work:

<span data-bind="text: ProjectId < 10 ? '0' + ProjectId.toString() : ProjectId"></span>

Or move this logic to your model instead:

vm.paddedProjectId = ko.computed(function() {
    return vm.ProjectId < 10 ? '0' + vm.ProjectId.toString() : vm.ProjectId;
});

This won't work for numbers below zero, nor will it pick up a dynamic number of zero's (e.g. if your numbers go beyond 100 you may want "005", etc). It may also have some iffy results with unexpected values for ProjectId, such as the empty string. For those cases refer to the question mentioned in comments.

PS. The function you're using is Number.toString that expects a radix argument; useful in its own right but not quite what you're looking for I think.

Community
  • 1
  • 1
Jeroen
  • 60,696
  • 40
  • 206
  • 339
0

As told here, use use the zeroFill function to add leading zeros.

vm.paddedProjectId = ko.computed(function() {
return vm.zeroFill(vm.ProjectId());
});
Community
  • 1
  • 1
Thaadikkaaran
  • 5,088
  • 7
  • 37
  • 59