Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

How to format a string using fixed-width fields in TypeScript

5 Answers

0 votes
/**
 * Formats a record using fixed-width fields.
 *
 * Name   : left-aligned, width 15
 * Age    : right-aligned, width 10
 * Salary : right-aligned, width 12, 2 decimal places
 */
function formatRecord(
    name: string,
    age: number,
    salary: number
): string {
    const nameField: string = name.padEnd(15, ' ');
    const ageField: string = age.toString().padStart(10, ' ');
    const salaryField: string = salary.toFixed(2).padStart(12, ' ');

    return nameField + ageField + salaryField;
}

// Store the formatted string in a variable
const result: string = formatRecord("Pandora", 58, 155000);

console.log(result);



/*
run:

Pandora                58   155000.00

*/

 



answered 3 days ago by avibootz
0 votes
const text: string = "Hello";

// Left-align in a field 10 characters wide
const leftAligned: string = text.padEnd(10, ' ');

console.log("|" + leftAligned + "|");



/*
run:

|Hello     |

*/

 



answered 3 days ago by avibootz
0 votes
const value: number = 123;

// Right-align in a field 8 characters wide
const formatted: string = value.toString().padStart(8, ' ');

console.log("|" + formatted + "|");



/*
run:

|     123|

*/

 



answered 3 days ago by avibootz
0 votes
const value: number = 123;

// Pad with leading zeros to width 8
const formatted: string = value.toString().padStart(8, '0');

console.log(formatted);


/*
run:

00000123

*/

 



answered 3 days ago by avibootz
0 votes
// Formatting a table

// Sample data
const people: { name: string; age: number; salary: number }[] = [
    { name: "Falcon", age: 40, salary: 95000 },
    { name: "Emma", age: 32, salary: 82000 }
];

// Print header
console.log(
    "Name".padEnd(15) +
    "Age".padStart(10) +
    "Salary".padStart(12)
);

// Print data rows
for (const person of people) {
    console.log(
        person.name.padEnd(15) +
        person.age.toString().padStart(10) +
        person.salary.toFixed(2).padStart(12)
    );
}


/*
run:

Name                  Age      Salary
Falcon                 40    95000.00
Emma                   32    82000.00

*/

 



answered 3 days ago by avibootz
...