go中格式化方法

戈伍昂的领悟 / 2023-07-22 / 原文

将字典转换为json字符串

func FormatToJson(i any) string {
	res, _ := json.MarshalIndent(i, "", "   ")
	return string(res)
}

将byte切片转换为json字符串

func FormatBytesToJsion(d []byte) string {
	var data interface{}
	err := json.Unmarshal(d, &data)
	if err != nil {
		fmt.Println("error unmarshalling json:", err)
		os.Exit(1)
	}
	res, _ := json.MarshalIndent(data, "", "   ")
	return string(res)
}

将时间段转换成时间字符串

func FormatTimeToString(d time.Duration) (string, error) {
	if d < 0 {
		return "", fmt.Errorf("时间段不应为负数")
	}

	seconds := d.Seconds()
	if seconds < 60 {
		return fmt.Sprintf("%-5.2f%6s", seconds, "seconds"), nil
	}

	minutes := d.Minutes()
	if minutes < 60 {
		return fmt.Sprintf("%-5.1f%6s", minutes, "minutes"), nil
	}

	hours := d.Hours()
	if hours < 24 {
		return fmt.Sprintf("%-5.1f%6s", hours, "hours"), nil
	}

	days := d.Hours() / 24
	if days < 7 {
		return fmt.Sprintf("%-5.0f%6s", days, "days"), nil
	}

	weeks := d.Hours() / (24 * 7)
	if weeks < 4 {
		return fmt.Sprintf("%-5.0f%6s", weeks, "weeks"), nil
	}

	months := d.Hours() / (24 * 30)
	if months < 12 {
		return fmt.Sprintf("%-5.0f%6s", months, "months"), nil
	}

	years := d.Hours() / (24 * 365)
	return fmt.Sprintf("%-5.0f%6s", years, "years"), nil
}

// 形如 
// 6.5   hours   
// 2      days
// 3     weeks
// 3    months
// 2     years

将存储大小转换成字符串

func isInteger0(f float64) bool {
	f1 := fmt.Sprintf("%.2f", f)
	return strings.HasSuffix(f1, ".00")
}
func isInteger1(f float64) bool {
	f1 := fmt.Sprintf("%.2f", f)
	return strings.HasSuffix(f1, "0")
}

func formatNumber(f float64) string {
	if isInteger0(f) {
		return fmt.Sprintf("%.0f", f)
	}
	if isInteger1(f) {
		return fmt.Sprintf("%.1f", f)
	}
	return fmt.Sprintf("%.2f", f)
}

func FormatStorageToString(bytes int64) (string, error) {
	if bytes < 0 {
		return "", fmt.Errorf("bytes should not be negative")
	}

	const (
		ByteSize = 1
		KiloByte = 1024
		MegaByte = 1024 * KiloByte
		GigaByte = 1024 * MegaByte
		TeraByte = 1024 * GigaByte
	)

	if bytes < KiloByte {
		return formatNumber(float64(bytes)) + " b", nil
	} else if bytes < MegaByte {
		return formatNumber(float64(bytes)/float64(KiloByte)) + "KB", nil
	} else if bytes < GigaByte {
		return formatNumber(float64(bytes)/float64(MegaByte)) + "MB", nil
	} else if bytes < TeraByte {
		return formatNumber(float64(bytes)/float64(GigaByte)) + "GB", nil
	} else {
		return formatNumber(float64(bytes)/float64(TeraByte)) + "TB", nil
	}
}

// 形如
// 779.32MB
//   1.65GB
// 753.31MB
// 234.22KB