TypeScript中實現(xiàn)字符串格式化及數(shù)值對齊
引言
字符串格式化是處理文本展示的常見需求,尤其在需要規(guī)范數(shù)值、日期等數(shù)據(jù)的顯示格式時非常重要。TypeScript 雖然沒有像 Python 的format()函數(shù)那樣原生提供一站式格式化工具,但可以通過模板字符串、字符串方法和正則表達(dá)式組合實現(xiàn)類似功能,包括數(shù)值的左右對齊等場景。
一、基礎(chǔ)字符串格式化(類似 Python f-string)
Python 中常用f-string或str.format()進(jìn)行變量嵌入,TypeScript 的模板字符串(反引號+${})是對等實現(xiàn),支持直接嵌入變量和表達(dá)式。
示例:基本變量嵌入
// 定義變量
const name: string = "Alice";
const age: number = 30;
const score: number = 95.5;
// 基礎(chǔ)格式化:嵌入變量
const info: string = `${name} is ${age} years old, score: ${score}`;
console.log(info); // 輸出:Alice is 30 years old, score: 95.5
示例:表達(dá)式計算
模板字符串中可直接執(zhí)行表達(dá)式,類似 Pythonf-string中的{x + y}:
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 位小數(shù)
const finalPrice: string = `折后價:${(price * discount).toFixed(2)}元`;
// 輸出:"折后價:79.92元"
二、數(shù)值型格式化(保留小數(shù)、千位分隔)
Python 中可用"{:.2f}".format(3.1415)保留小數(shù),TypeScript 可通過toFixed()、Intl.NumberFormat等方法實現(xiàn)。
1. 保留指定小數(shù)位數(shù)
const pi: number = 3.1415926;
// 保留2位小數(shù)(類似Python "{:.2f}".format(pi))
console.log(pi.toFixed(2)); // 輸出:3.14(返回字符串類型)
// 保留0位小數(shù)(取整)
console.log(pi.toFixed(0)); // 輸出:3
2. 千位分隔符(數(shù)字格式化)
const largeNum: number = 1234567.89;
// 千位分隔,保留2位小數(shù)(類似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
三、數(shù)值的左右對齊(固定寬度)
Python 中可用"{:>10d}".format(123)實現(xiàn)右對齊(占 10 個字符寬度),TypeScript 可通過padStart()和padEnd()實現(xiàn)類似的固定寬度對齊。
核心方法:
- padStart(targetLength, padString):在字符串左側(cè)填充指定字符,達(dá)到目標(biāo)長度(右對齊效果)。
- padEnd(targetLength, padString):在字符串右側(cè)填充指定字符,達(dá)到目標(biāo)長度(左對齊效果)。
1. 整數(shù)右對齊(固定寬度)
const num: number = 123;
const width: number = 10; // 總寬度10個字符
// 右對齊:數(shù)字轉(zhuǎn)字符串后,左側(cè)補空格(類似Python "{:>10d}".format(123))
const rightAligned: string = num.toString().padStart(width, ' ');
console.log(`|${rightAligned}|`); // 輸出:| 123|(左側(cè)7個空格+123,共10位)
// 需求:將數(shù)值轉(zhuǎn)為 5 位右對齊(不足補零)
const score1: number = 85;
const score2: number = 9;
const score3: number = 95;
// 方法:轉(zhuǎn)字符串后用 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. 整數(shù)左對齊(固定寬度)
const num: number = 456;
const width: number = 10;
// 左對齊:數(shù)字轉(zhuǎn)字符串后,右側(cè)補空格(類似Python "{:<10d}".format(456))
const leftAligned: string = num.toString().padEnd(width, ' ');
console.log(`|${leftAligned}|`); // 輸出:|456 |(456+右側(cè)7個空格,共10位)
// 需求:將數(shù)值轉(zhuǎn)為 5 位左對齊(不足補空格)
const num1: number = 123;
const num2: number = 4567;
const num3: number = 89;
// 方法:轉(zhuǎn)字符串后用 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 "
// 需求:根據(jù)數(shù)組中最大數(shù)值的長度,動態(tài)右對齊所有數(shù)值
const numbers: number[] = [12, 345, 6, 7890];
const maxLen: number = Math.max(...numbers.map(n => n.toString().length)); // 最大長度 4
// 生成對齊后的字符串?dāng)?shù)組
const aligned: string[] = numbers.map(n =>
n.toString().padStart(maxLen, " ") // 右對齊,補空格
);
console.log(aligned.join(" | "));
// 輸出:" 12 | 345 | 6 | 7890"
3. 帶小數(shù)的數(shù)值對齊
const decimalNum: number = 78.9;
const width: number = 10;
// 先保留1位小數(shù),再右對齊
const formattedNum: string = decimalNum.toFixed(1); // "78.9"
const rightAlignedDecimal: string = formattedNum.padStart(width, ' ');
console.log(`|${rightAlignedDecimal}|`); // 輸出:| 78.9|(左側(cè)6個空格+78.9,共10位)
const population: number = 1234567;
// 通用千位分隔符(英文環(huán)境)
const withCommas: string = population.toLocaleString(); // "1,234,567"
// 自定義分隔符(如中文環(huán)境)
const withChineseCommas: string = population.toLocaleString("zh-CN"); // "1,234,567"(效果相同)
const rate: number = 0.755;
// 保留 1 位小數(shù)的百分比
const percentage: string = (rate * 100).toFixed(1) + "%"; // "75.5%"
const amount: number = 1234.56;
// 美元格式(英文環(huán)境)
const usd: string = amount.toLocaleString("en-US", {
style: "currency",
currency: "USD",
}); // "$1,234.56"
// 人民幣格式(中文環(huán)境)
const cny: string = amount.toLocaleString("zh-CN", {
style: "currency",
currency: "CNY",
}); // "¥1,234.56"
4. 自定義填充字符(非空格)
const num: number = 99;
const width: number = 8;
// 用0填充左側(cè)(右對齊,類似Python "{:0>8d}".format(99))
const zeroPadded: string = num.toString().padStart(width, '0');
console.log(zeroPadded); // 輸出:00000099(6個0+99,共8位)
/**
* 格式化數(shù)值+單位(右對齊數(shù)值,固定單位寬度)
* @param value 數(shù)值
* @param unit 單位(如 "ms")
* @param totalWidth 總寬度(數(shù)值+單位的總長度)
*/
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; // 數(shù)值部分可用寬度
return valueStr.padStart(totalValueWidth, " ") + unitStr;
}
// 使用示例
console.log(formatWithUnit(100, "ms", 6)); // " 100ms"(總寬度6:3位數(shù)值+3位單位)
console.log(formatWithUnit(50, "ms", 6)); // " 50ms"
console.log(formatWithUnit(1234, "ms", 8)); // " 1234ms"(總寬度8:4位數(shù)值+3位單位+1空格?需調(diào)整邏輯)
四、綜合案例:表格格式化輸出
模擬 Python 中格式化表格的場景,用 TypeScript 實現(xiàn)列對齊:
// 數(shù)據(jù)
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));
// 內(nèi)容行(名稱左對齊,價格和庫存右對齊)
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);
});
輸出結(jié)果:
Name Price Stock ------------------------ Apple 5.99 120 Banana 2.50 300 Orange 3.75 80
五、與 Python 格式化的對比總結(jié)
| 格式化需求 | Python 代碼示例 | TypeScript 代碼示例 |
|---|---|---|
| 變量嵌入 | f"Name: {name}" | ${name}(模板字符串) |
| 保留 2 位小數(shù) | "{:.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') |
通過模板字符串結(jié)合padStart()、padEnd()、toFixed()等方法,TypeScript 可以靈活實現(xiàn)各種字符串格式化需求,尤其是數(shù)值的對齊顯示。初學(xué)者只需掌握這些基礎(chǔ)方法的組合,就能應(yīng)對大部分格式化場景。
以上就是TypeScript中實現(xiàn)字符串格式化及數(shù)值對齊的詳細(xì)內(nèi)容,更多關(guān)于TypeScript字符串格式化及數(shù)值對齊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于javascript中偽數(shù)組和真數(shù)組的一些小秘密
在javascript中,偽數(shù)組又稱類數(shù)組,是一個類似數(shù)組的對象,是一種按照索引存儲數(shù)據(jù)且具有l(wèi)ength屬性的對象,下面這篇文章主要給大家介紹了關(guān)于javascript中偽數(shù)組和真數(shù)組的一些小秘密,需要的朋友可以參考下2022-08-08
JavaScript通過極大極小值算法實現(xiàn)AI井字棋游戲
極小極大值搜索算法是一種零和算法,是用來最小化對手的利益,最大化自己的利益的算法。極小極大之搜索算法常用于棋類游戲等雙方較量的游戲和程序,算是一種電腦AI算法。本文將介紹通過這個算法實現(xiàn)的一個井字棋游戲,需要的可以參考一下2021-12-12
javascript設(shè)計模式 – 裝飾模式原理與應(yīng)用實例分析
這篇文章主要介紹了javascript設(shè)計模式 – 裝飾模式,結(jié)合實例形式分析了javascript裝飾模式基本概念、原理、應(yīng)用場景及操作注意事項,需要的朋友可以參考下2020-04-04
JavaScript實現(xiàn)復(fù)制粘貼剪切功能三種方法
這篇文章主要給大家介紹了關(guān)于JavaScript實現(xiàn)復(fù)制粘貼剪切功能的相關(guān)資料,在實際案例的操作過程中,不少人都會遇到這樣的開發(fā)需求,文中通過代碼將三種方法介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
JavaScript+Canvas模擬實現(xiàn)支付寶畫年兔游戲
接近過年了,支付寶的集福的活動又開始了,集美們的五福集齊了沒有。每年的集?;顒佣加幸恍┬∮螒?,今年也不例外,畫年畫就是其中之一,本篇用canvas來寫一個畫年兔的游戲2023-01-01
layui實現(xiàn)圖片虛擬路徑上傳,預(yù)覽和刪除的例子
今天小編就為大家分享一篇layui實現(xiàn)圖片虛擬路徑上傳,預(yù)覽和刪除的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

