问题描述:
后端返回一个数字,单位是kb,而我要展示成 KB,MB 等形式。大概写一个工具函数,JS来实现
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
if (bytes === 0) return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
}
// 示例用法:
const sizeInKB = 10240; // 假设后端返回的数值是 10240 KB
const formattedSize = formatBytes(sizeInKB * 1024); // 将 KB 转换为 Bytes 并格式化
console.log(formattedSize); // 输出 "10.00 MB"
用Python:
def format_bytes(size_in_bytes):
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
if size_in_bytes == 0:
return '0 Bytes'
i = int(math.floor(math.log(size_in_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_in_bytes / p, 2)
return f"{s} {sizes[i]}"
# 示例用法:
size_in_kb = 10240 # 假设输入为 KB
formatted_size = format_bytes(size_in_kb * 1024) # 转换为 Bytes 并格式化
print(formatted_size) # 输出 "10.0 MB"
用Java
public class SizeFormatter {
public static String formatBytes(long bytes) {
String[] sizes = {"Bytes", "KB", "MB", "GB", "TB", "PB"};
if (bytes == 0) return "0 Bytes";
int i = (int) Math.floor(Math.log(bytes) / Math.log(1024));
double formattedSize = bytes / Math.pow(1024, i);
return String.format("%.2f %s", formattedSize, sizes[i]);
}
public static void main(String[] args) {
long sizeInKB = 10240; // 假设输入为 KB
String formattedSize = formatBytes(sizeInKB * 1024); // 转换为 Bytes 并格式化
System.out.println(formattedSize); // 输出 "10.00 MB"
}
}
用 C#
using System;
class Program
{
static string FormatBytes(long bytes)
{
string[] sizes = { "Bytes", "KB", "MB", "GB", "TB", "PB" };
if (bytes == 0) return "0 Bytes";
int i = (int)Math.Floor(Math.Log(bytes) / Math.Log(1024));
double formattedSize = bytes / Math.Pow(1024, i);
return $"{formattedSize:F2} {sizes[i]}";
}
static void Main(string[] args)
{
long sizeInKB = 10240; // 假设输入为 KB
string formattedSize = FormatBytes(sizeInKB * 1024); // 转换为 Bytes 并格式化
Console.WriteLine(formattedSize); // 输出 "10.00 MB"
}
}
用GO
package main
import (
"fmt"
"math"
)
func formatBytes(bytes int64) string {
sizes := []string{"Bytes", "KB", "MB", "GB", "TB", "PB"}
if bytes == 0 {
return "0 Bytes"
}
i := int(math.Floor(math.Log(float64(bytes)) / math.Log(1024)))
formattedSize := float64(bytes) / math.Pow(1024, float64(i))
return fmt.Sprintf("%.2f %s", formattedSize, sizes[i])
}
func main() {
sizeInKB := int64(10240) // 假设输入为 KB
formattedSize := formatBytes(sizeInKB * 1024) // 转换为 Bytes 并格式化
fmt.Println(formattedSize) // 输出 "10.00 MB"
}