字节(1024)到字符串转换(1kb)?

时间:2022-11-28 21:39:05

I would like to know if there is a function in .NET which converts numeric bytes into the string with correct measurement?

我想知道。net中是否有一个函数可以将数字字节转换为正确的字符串。

Or we just need to follow old approach of dividing and holding the conversion units to get it done?

或者我们只需要遵循旧的方法来划分和保存转换单元来完成它?

1 个解决方案

#1


7  

No, there isn't.

不,没有。

You can write one like this:

你可以这样写:

public static string ToSizeString(this double bytes) {
    var culture = CultureInfo.CurrentUICulture;
    const string format = "#,0.0";

    if (bytes < 1024)
        return bytes.ToString("#,0", culture);
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " KB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " MB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " GB";
    bytes /= 1024;
    return bytes.ToString(format, culture) + " TB";
}

#1


7  

No, there isn't.

不,没有。

You can write one like this:

你可以这样写:

public static string ToSizeString(this double bytes) {
    var culture = CultureInfo.CurrentUICulture;
    const string format = "#,0.0";

    if (bytes < 1024)
        return bytes.ToString("#,0", culture);
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " KB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " MB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " GB";
    bytes /= 1024;
    return bytes.ToString(format, culture) + " TB";
}