go-humanize
是一个Go
语言库,旨在将数字
、时间
、容量
等转换为更易于人类理解的形式。它通过提供一系列格式化函数,帮助开发者将技术性的数据转换成人类可读的格式。
go-humanize
提供以下功能
go-humanize
通过这些功能,使得日志输出、用户界面或任何需要展示数字和时间的场景更加直观和易于理解。
项目地址:https://github.com/dustin/go-humanize
根据喜好可以将82854982
形如83 MB
或79 MiB
格式的字符串。
go// 生成SI大小的人类可读表示
// That file is 83 MB.
fmt.Printf("That file is %s.\n", humanize.Bytes(82854982))
// 生成IEC大小的人类可读表示
// That file is 79 MB.
fmt.Printf("That file is %s.\n", humanize.IBytes(82854982))
将时间格式话为相对时间字符串。
go// This was touched 7 hours ago.
fmt.Printf("This was touched %s.", humanize.Time(time.Now().Add(-7*time.Hour)))
将数字转换为千分位格式字符串
0 -> 0 100 -> 100 1000 -> 1,000 1000000000 -> 1,000,000,000 -100000 -> -100,000
go// You owe $6,582,491.
fmt.Printf("You owe $%s.\n", humanize.Comma(6582491))
将数字转换为序数格式字符串
0 -> 0th 1 -> 1st 2 -> 2nd 3 -> 3rd 4 -> 4th [...]
go// You are my 193rd best friend.
fmt.Printf("You're my %s best friend.", humanize.Ordinal(193))
更好的float64格式化方式,可以将小数部分多余的0
移除。
gofmt.Printf("%f", 2.24) // 2.240000
fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24
fmt.Printf("%f", 2.0) // 2.000000
fmt.Printf("%s", humanize.Ftoa(2.0)) // 2
将数字格式化为国际单位制字符串。
gohumanize.SI(0.00000000223, "M") // 2.23 nM
本文作者:蒋固金
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!