Golang中的字节单位转换指南

发表时间: 2024-05-28 21:25
package mainimport ("fmt")func main() {    fmt.Println(formatFileSize(128 << 30)) // 位运算符 由字节转换成GB    fmt.Println(formatFileSize(112 << 30))    fmt.Println(formatFileSize(10 << 20))}// 字节的单位转换 保留两位小数func formatFileSize(fileSize int64) (size string) {    if fileSize < 1024 {        //return strconv.FormatInt(fileSize, 10) + "B"        return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))    } else if fileSize < (1024 * 1024) {        return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))    } else if fileSize < (1024 * 1024 * 1024) {    		return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))    } else if fileSize < (1024 * 1024 * 1024 * 1024) {    		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))    } else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {    		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))    } else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)    		return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))    }}/*128.00GB112.00GB10.00MB*/