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.
In this section custom solution on how to pad any characters on the right side is presented.
xxxxxxxxxx
1
function padRight(number: number, length: number, character?: string): String {
2
if (character == null) {
3
character = ' ';
4
}
5
let result = new String(number);
6
for (let i = result.length; i < length; ++i) {
7
result += character;
8
}
9
return result;
10
}
11
12
// Usage example:
13
14
console.log(padRight(123, 2) + ' ' + padRight(456, 2));
15
console.log(padRight(123, 4) + ' ' + padRight(456, 4));
16
console.log(padRight(123, 6, ' ') + ' ' + padRight(456, 6, ' '));
17
console.log(padRight(123, 6, '*'));
18
console.log(padRight(123, 6, '.'));
19
console.log(padRight(123, 6, '0'));
Output:
xxxxxxxxxx
1
123 456
2
123 456
3
123 456
4
123***
5
123...
6
123000
ECMAScript 2017 introduced a function that pads numbers.
In this section presented code uses copied method from the polyfill library. Before using padStart()
method, install ts-polyfill
package first.
xxxxxxxxxx
1
npm install ts-polyfill
Example:
xxxxxxxxxx
1
// https://github.com/ryanelian/ts-polyfill
2
// https://developer.mozilla.org/en-US/docs/Web/TypeScript/Reference/Global_Objects/String/padEnd
3
4
import 'ts-polyfill/lib/es2017-string';
5
6
const text1 = '123';
7
const text2 = '456';
8
9
console.log(text1.padEnd(2) + ' ' + text2.padEnd(2));
10
console.log(text1.padEnd(4) + ' ' + text2.padEnd(4));
11
console.log(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
12
console.log(text1.padEnd(6, '*'));
13
console.log(text1.padEnd(6, '.'));
14
console.log(text1.padEnd(6, '0'));
Output:
xxxxxxxxxx
1
123 456
2
123 456
3
123 456
4
123***
5
123...
6
123000