Skip to content

Human readable formatting and input parsing for Go, with i18n support. Easily extendable with new languages.

License

Notifications You must be signed in to change notification settings

pawelszydlo/humanize

Repository files navigation

humanize GoDoc Go Report Card Build Status codecov

Human readable formatting and input parsing for Go, with i18n support. Easily extendable with new languages.

Supported languages

  • English
  • Polish

Table of contents


Features

Decode duration from human input

duration, _ := humanizer.ParseDuration("2 days, 5 hours and 40 seconds")
fmt.Println(duration) 
// Prints: 53h0m40s

Humanize date difference

firstDate := time.Date(2017, 3, 21, 12, 30, 15, 0, time.UTC)
secondDate := time.Date(2017, 6, 21, 0, 0, 0, 0, time.UTC)

Approximate mode:

fmt.Println(humanizer.TimeDiff(firstDate, secondDate, false))
// Prints: in 3 months

Precise mode:

fmt.Println(humanizer.TimeDiff(secondDate, firstDate, true))
// Prints: 3 months, 1 day, 11 hours, 29 minutes and 45 seconds ago

Pretty print timestamps

fmt.Println(humanizer.SecondsToTimeString(67))
// Prints: 01:07

Add decimal separators to numbers

Uses x/text/number and is locale aware.

fmt.Println(humanizer.HumanizeNumber(1234.567, 2))
// Prints: 1,234.57

Decode value from human input with a prefix

value, _ := humanizer.ParsePrefix("1.5k")
fmt.Println(value)
// Prints: 1500

Bit prefixes are recognized as well:

value, _ := humanizer.ParsePrefix("1.5Ki")
fmt.Println(value)
// Prints: 1536

NOTE: ParsePrefix will return a precise value (big.Float), so you might get fractions where you wouldn't expect them (e.g. bytes). It's up to you to handle that.

Humanize big numbers with prefixes

Quick usage:

fmt.Println(humanizer.SiPrefixFast(174512))
// Prints: 174.5k

Controlled usage:

fmt.Println(humanizer.SiPrefix(1440000, 2, 1000, false))
// Prints: 1.44 mega

Using bit prefixes instead of metric:

fmt.Println(humanizer.BitPrefixFast(1509949))
// Prints: 1.44Mi

Humanize parts of one

Avoid leading zeroes:

fmt.Println(humanizer.HumanizeParts(0.25, 0))
// Prints: 25%
fmt.Println(humanizer.HumanizeParts(0.0023, 0))
// Prints: 2‰

Allow leading zeroes to avoid jumping to a smaller unit:

fmt.Println(humanizer.HumanizeParts(0.0023, 1))
// Prints: 0.23%

TODO

  • Smarter imprecise mode for time durations.
  • More features?

About

Human readable formatting and input parsing for Go, with i18n support. Easily extendable with new languages.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages