EN
TypeScript - pad right number in string with zeros or spaces to get determined length
0
points
In TypeScript it is possible to pad any number with some character in the following ways:
- with simple custom method (Example 1),
- with
padEnd
method placed insideString
class (Example 2 and 3) - introduced in ES2017 - is not supported in older browsers.
1. Custom solution example
In this section custom solution on how to pad any characters on the right side is presented.
function padRight(number: number, length: number, character?: string): String {
if (character == null) {
character = ' ';
}
let result = new String(number);
for (let i = result.length; i < length; ++i) {
result += character;
}
return result;
}
// Usage example:
console.log(padRight(123, 2) + ' ' + padRight(456, 2));
console.log(padRight(123, 4) + ' ' + padRight(456, 4));
console.log(padRight(123, 6, ' ') + ' ' + padRight(456, 6, ' '));
console.log(padRight(123, 6, '*'));
console.log(padRight(123, 6, '.'));
console.log(padRight(123, 6, '0'));
Output:
123 456
123 456
123 456
123***
123...
123000
2. Polifill example
ECMAScript 2017 introduced a function that pads numbers.
2.1. Inline code example
In this section presented code uses copied method from the polyfill library. Before using padStart()
method, install ts-polyfill
package first.
npm install ts-polyfill
Example:
// https://github.com/ryanelian/ts-polyfill
// https://developer.mozilla.org/en-US/docs/Web/TypeScript/Reference/Global_Objects/String/padEnd
import 'ts-polyfill/lib/es2017-string';
const text1 = '123';
const text2 = '456';
console.log(text1.padEnd(2) + ' ' + text2.padEnd(2));
console.log(text1.padEnd(4) + ' ' + text2.padEnd(4));
console.log(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
console.log(text1.padEnd(6, '*'));
console.log(text1.padEnd(6, '.'));
console.log(text1.padEnd(6, '0'));
Output:
123 456
123 456
123 456
123***
123...
123000