2025-01-27
Go
00

目录

第一部分 概述
第二部分 常用操作
2.1 容量
2.2 时间
2.3 千分位
2.4 序数
2.5 Ftoa
国际单位制

第一部分 概述

go-humanize是一个Go语言库,旨在将数字时间容量等转换为更易于人类理解的形式。它通过提供一系列格式化函数,帮助开发者将技术性的数据转换成人类可读的格式。

go-humanize提供以下功能

  • 容量转换:将字节转换为更易读的单位,如KB、MB、GB等。例如,humanize.Bytes(52854982)会输出53MB。
  • 时间转换:将时间戳转换为相对时间,如7 hours ago或3 days from now。例如,humanize.Time(someTimeInstance)会输出类似7 hours ago的字符串。
  • 千分位转换:在数字中添加逗号,使其更易于阅读。例如,humanize.Comma(1000000000)会输出1,000,000,000。
  • 序数转换:将数字转换为序数形式,如1st、2nd、3rd等。例如,humanize.Ordinal(193)会输出193rd。
  • 浮点数转换:将浮点数转换为千分位形式,如humanize.Commaf(834142.32)会输出834,142.32。
  • 大数字处理:支持大数字的处理,如humanize.BigBytes和humanize.BigComma函数。
  • 自定义相对时间:允许自定义相对时间的格式,通过humanize.CustomRelTime函数。

go-humanize通过这些功能,使得日志输出、用户界面或任何需要展示数字和时间的场景更加直观和易于理解。

项目地址:https://github.com/dustin/go-humanize

第二部分 常用操作

2.1 容量

根据喜好可以将82854982形如83 MB79 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))

2.2 时间

将时间格式话为相对时间字符串。

go
// This was touched 7 hours ago. fmt.Printf("This was touched %s.", humanize.Time(time.Now().Add(-7*time.Hour)))

2.3 千分位

将数字转换为千分位格式字符串

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))

2.4 序数

将数字转换为序数格式字符串

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))

2.5 Ftoa

更好的float64格式化方式,可以将小数部分多余的0移除。

go
fmt.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

国际单位制

将数字格式化为国际单位制字符串。

go
humanize.SI(0.00000000223, "M") // 2.23 nM
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:蒋固金

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!