Skip to content

Commit f2145db

Browse files
authored
Merge pull request #20 from yongtang/26300-docker-images-3-fractional-digits
Add `HumanSizeWithPrecision` function
2 parents 2c1805a + e2f6241 commit f2145db

1 file changed

Lines changed: 17 additions & 5 deletions

File tree

size.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,22 +37,34 @@ var (
3737
var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
3838
var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
3939

40-
// CustomSize returns a human-readable approximation of a size
41-
// using custom format.
42-
func CustomSize(format string, size float64, base float64, _map []string) string {
40+
func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) {
4341
i := 0
4442
unitsLimit := len(_map) - 1
4543
for size >= base && i < unitsLimit {
4644
size = size / base
4745
i++
4846
}
49-
return fmt.Sprintf(format, size, _map[i])
47+
return size, _map[i]
48+
}
49+
50+
// CustomSize returns a human-readable approximation of a size
51+
// using custom format.
52+
func CustomSize(format string, size float64, base float64, _map []string) string {
53+
size, unit := getSizeAndUnit(size, base, _map)
54+
return fmt.Sprintf(format, size, unit)
55+
}
56+
57+
// HumanSizeWithPrecision allows the size to be in any precision,
58+
// instead of 4 digit precision used in units.HumanSize.
59+
func HumanSizeWithPrecision(size float64, precision int) string {
60+
size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
61+
return fmt.Sprintf("%.*g %s", precision, size, unit)
5062
}
5163

5264
// HumanSize returns a human-readable approximation of a size
5365
// capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
5466
func HumanSize(size float64) string {
55-
return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs)
67+
return HumanSizeWithPrecision(size, 4)
5668
}
5769

5870
// BytesSize returns a human-readable size in bytes, kibibytes,

0 commit comments

Comments
 (0)