Just wondering if .NET provides a clean way to do this:
int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
y = string.Format("{0:n1} KB", x / 1024f);
}
etc...
Just wondering if .NET provides a clean way to do this:
int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
y = string.Format("{0:n1} KB", x / 1024f);
}
etc...
I would solve it using
Extension methods
,Math.Pow
function andEnums
:and use it like:
Checkout the ByteSize library. It's the
System.TimeSpan
for bytes!It handles the conversion and formatting for you.
It also does string representation and parsing.
How about:
E.g. call like
Will result in output
I have combined some of the answers here into two methods that work great. The second method below will convert from a bytes string (like 1.5.1 GB) back to bytes (like 1621350140) as a long type value. I hope this is useful to others looking for a solution to convert bytes to a string and back into bytes.
Based on NeverHopeless's elegant solution:
Maybe there are excessive comments, but I tend to leave them to prevent myself from making the same mistakes over on future visits...
The short version of the most voted answer has problems with TB values.
I adjusted it appropriately to handle also tb values and still without a loop and also added a little error checking for negative values. Here's my solution: