TypeScript 中字符串格式化及数值对齐的实现

TypeScript 中字符串格式化及数值对齐的实现

字符串格式化是处理文本展示的常见需求,尤其在需要规范数值、日期等数据的显示格式时非常重要。TypeScript 虽然没有像 Python 的format()函数那样原生提供一站式格式化工具,但可以通过模板字符串、字符串方法和正则表达式组合实现类似功能,包括数值的左右对齐等场景。

一、基础字符串格式化(类似 Python f-string)

Python 中常用f-string或str.format()进行变量嵌入,TypeScript 的模板字符串(反引号+${})是对等实现,支持直接嵌入变量和表达式。

示例:基本变量嵌入

ini 复制代码
// 定义变量
const name: string = "Alice";
const age: number = 30;
const score: number = 95.5;
// 基础格式化:嵌入变量
const info: string = `${name} is ${age} years old, score: ${score}`;
console.log(info); // 输出:Alice is 30 years old, score: 95.5

示例:表达式计算

模板字符串中可直接执行表达式,类似 Pythonf-string中的{x + y}:

typescript 复制代码
const a: number = 10;
const b: number = 20;
console.log(`Sum: ${a + b}`); // 输出:Sum: 30
console.log(`Double of ${a}: ${a * 2}`); // 输出:Double of 10: 20

const price: number = 99.9;
const discount: number = 0.8;
// 计算折后价并保留 2 位小数
const finalPrice: string = `折后价:${(price * discount).toFixed(2)}元`; 
// 输出:"折后价:79.92元"

二、数值型格式化(保留小数、千位分隔)

Python 中可用"{:.2f}".format(3.1415)保留小数,TypeScript 可通过toFixed()、Intl.NumberFormat等方法实现。

1. 保留指定小数位数

lua 复制代码
const pi: number = 3.1415926;
// 保留2位小数(类似Python "{:.2f}".format(pi))
console.log(pi.toFixed(2)); // 输出:3.14(返回字符串类型)
// 保留0位小数(取整)
console.log(pi.toFixed(0)); // 输出:3

2. 千位分隔符(数字格式化)

typescript 复制代码
const largeNum: number = 1234567.89;
// 千位分隔,保留2位小数(类似Python "{:,.2f}".format(largeNum))
const formatted: string = new Intl.NumberFormat('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}).format(largeNum);
console.log(formatted); // 输出:1,234,567.89

三、数值的左右对齐(固定宽度)

Python 中可用"{:>10d}".format(123)实现右对齐(占 10 个字符宽度),TypeScript 可通过padStart()和padEnd()实现类似的固定宽度对齐。

核心方法:

  • padStart(targetLength, padString):在字符串左侧填充指定字符,达到目标长度(右对齐效果)。
  • padEnd(targetLength, padString):在字符串右侧填充指定字符,达到目标长度(左对齐效果)。

1. 整数右对齐(固定宽度)

ini 复制代码
const num: number = 123;
const width: number = 10; // 总宽度10个字符
// 右对齐:数字转字符串后,左侧补空格(类似Python "{:>10d}".format(123))
const rightAligned: string = num.toString().padStart(width, ' ');
console.log(`|${rightAligned}|`); // 输出:|       123|(左侧7个空格+123,共10位)

// 需求:将数值转为 5 位右对齐(不足补零)
const score1: number = 85;
const score2: number = 9;
const score3: number = 95;

// 方法:转字符串后用 padStart(总长度, "0")
const alignRight1: string = score1.toString().padStart(5, "0"); // "00085"
const alignRight2: string = score2.toString().padStart(5, "0"); // "00009"
const alignRight3: string = score3.toString().padStart(5, "0"); // "00095"

console.log([alignRight1, alignRight2, alignRight3].join(" ")); 
// 输出:"00085 00009 00095"

2. 整数左对齐(固定宽度)

typescript 复制代码
const num: number = 456;
const width: number = 10;
// 左对齐:数字转字符串后,右侧补空格(类似Python "{:<10d}".format(456))
const leftAligned: string = num.toString().padEnd(width, ' ');
console.log(`|${leftAligned}|`); // 输出:|456       |(456+右侧7个空格,共10位)

// 需求:将数值转为 5 位左对齐(不足补空格)
const num1: number = 123;
const num2: number = 4567;
const num3: number = 89;

// 方法:转字符串后用 padEnd(总长度, 填充字符)
const alignLeft1: string = num1.toString().padEnd(5, " "); // "123  "(5位,右补空格)
const alignLeft2: string = num2.toString().padEnd(5, " "); // "4567 "
const alignLeft3: string = num3.toString().padEnd(5, " "); // "89   "

console.log([alignLeft1, alignLeft2, alignLeft3].join("|")); 
// 输出:"123  |4567 |89   "


// 需求:根据数组中最大数值的长度,动态右对齐所有数值
const numbers: number[] = [12, 345, 6, 7890];
const maxLen: number = Math.max(...numbers.map(n => n.toString().length)); // 最大长度 4

// 生成对齐后的字符串数组
const aligned: string[] = numbers.map(n => 
  n.toString().padStart(maxLen, " ") // 右对齐,补空格
);

console.log(aligned.join(" | ")); 
// 输出:"  12 |  345 |    6 | 7890"

3. 带小数的数值对齐

php 复制代码
const decimalNum: number = 78.9;
const width: number = 10;
// 先保留1位小数,再右对齐
const formattedNum: string = decimalNum.toFixed(1); // "78.9"
const rightAlignedDecimal: string = formattedNum.padStart(width, ' ');
console.log(`|${rightAlignedDecimal}|`); // 输出:|      78.9|(左侧6个空格+78.9,共10位)

const population: number = 1234567;
// 通用千位分隔符(英文环境)
const withCommas: string = population.toLocaleString(); // "1,234,567"

// 自定义分隔符(如中文环境)
const withChineseCommas: string = population.toLocaleString("zh-CN"); // "1,234,567"(效果相同)

const rate: number = 0.755;
// 保留 1 位小数的百分比
const percentage: string = (rate * 100).toFixed(1) + "%"; // "75.5%"

const amount: number = 1234.56;
// 美元格式(英文环境)
const usd: string = amount.toLocaleString("en-US", {
  style: "currency",
  currency: "USD",
}); // "$1,234.56"

// 人民币格式(中文环境)
const cny: string = amount.toLocaleString("zh-CN", {
  style: "currency",
  currency: "CNY",
}); // "¥1,234.56"

4. 自定义填充字符(非空格)

typescript 复制代码
const num: number = 99;
const width: number = 8;
// 用0填充左侧(右对齐,类似Python "{:0>8d}".format(99))
const zeroPadded: string = num.toString().padStart(width, '0');
console.log(zeroPadded); // 输出:00000099(6个0+99,共8位)

/**
 * 格式化数值+单位(右对齐数值,固定单位宽度)
 * @param value 数值
 * @param unit 单位(如 "ms")
 * @param totalWidth 总宽度(数值+单位的总长度)
 */
function formatWithUnit(value: number, unit: string, totalWidth: number): string {
  const valueStr: string = value.toString();
  const unitStr: string = unit.padStart(3); // 单位固定占3位(如 " ms")
  const totalValueWidth: number = totalWidth - unitStr.length; // 数值部分可用宽度
  return valueStr.padStart(totalValueWidth, " ") + unitStr;
}

// 使用示例
console.log(formatWithUnit(100, "ms", 6)); // "  100ms"(总宽度6:3位数值+3位单位)
console.log(formatWithUnit(50, "ms", 6));  // "   50ms"
console.log(formatWithUnit(1234, "ms", 8)); // "  1234ms"(总宽度8:4位数值+3位单位+1空格?需调整逻辑)

四、综合案例:表格格式化输出

模拟 Python 中格式化表格的场景,用 TypeScript 实现列对齐:

ini 复制代码
// 数据
const data = [
  { name: "Apple", price: 5.99, stock: 120 },
  { name: "Banana", price: 2.5, stock: 300 },
  { name: "Orange", price: 3.75, stock: 80 }
];
// 定义各列宽度
const nameWidth = 10;
const priceWidth = 8;
const stockWidth = 6;
// 表头
console.log(
  "Name".padEnd(nameWidth, ' ') +
  "Price".padStart(priceWidth, ' ') +
  "Stock".padStart(stockWidth, ' ')
);
// 分隔线
console.log('-'.repeat(nameWidth + priceWidth + stockWidth));
// 内容行(名称左对齐,价格和库存右对齐)
data.forEach(item => {
  const name = item.name.padEnd(nameWidth, ' ');
  const price = item.price.toFixed(2).padStart(priceWidth, ' ');
  const stock = item.stock.toString().padStart(stockWidth, ' ');
  console.log(name + price + stock);
});

输出结果

markdown 复制代码
Name      Price  Stock
------------------------
Apple      5.99    120
Banana     2.50    300
Orange     3.75     80

五、与 Python 格式化的对比总结

格式化需求 Python 代码示例 TypeScript 代码示例
变量嵌入 f"Name: {name}" ${name}(模板字符串)
保留 2 位小数 "{:.2f}".format(3.1415) 3.1415.toFixed(2)
千位分隔符 "{:,.2f}".format(12345) new Intl.NumberFormat().format(12345)
右对齐(宽 10) "{:>10d}".format(123) 123.toString().padStart(10, ' ')
左对齐(宽 10) "{:<10d}".format(123) 123.toString().padEnd(10, ' ')
0 填充右对齐(宽 8) "{:0>8d}".format(99) 99.toString().padStart(8, '0')

通过模板字符串结合padStart()、padEnd()、toFixed()等方法,TypeScript 可以灵活实现各种字符串格式化需求,尤其是数值的对齐显示。初学者只需掌握这些基础方法的组合,就能应对大部分格式化场景。

相关推荐
小五1271 分钟前
数据科学与计算实例应用
开发语言·python
站大爷IP11 分钟前
Python类型注解:让代码“开口说话”的隐形助手
python
站大爷IP38 分钟前
Python多态实战:从基础到高阶的“魔法”应用指南
python
Hilaku41 分钟前
为什么我坚持用git命令行,而不是GUI工具?
前端·javascript·git
码界筑梦坊1 小时前
108-基于Python的中国古诗词数据可视化分析系统
python·信息可视化·数据分析·django·毕业设计·numpy
歪歪1001 小时前
Vue原理与高级开发技巧详解
开发语言·前端·javascript·vue.js·前端框架·集成学习
用户2519162427111 小时前
Canvas之画图板
前端·javascript·canvas
紫金修道1 小时前
python安装部署rknn-toolkit2(ModuleNotFoundError: No module named ‘rknn_toolkit2‘)
开发语言·python
EndingCoder2 小时前
Next.js API 路由:构建后端端点
开发语言·前端·javascript·ecmascript·全栈·next.js·api路由
阳火锅3 小时前
# 🛠 被老板逼出来的“表格生成器”:一个前端的自救之路
前端·javascript·面试