root / trunk / Pithos.Client.WPF / FileProperties / SizeExtensions.cs @ 42800be8
History | View | Annotate | Download (1 kB)
1 |
using System; |
---|---|
2 |
using System.Collections.Generic; |
3 |
using System.Linq; |
4 |
using System.Text; |
5 |
|
6 |
namespace Pithos.Client.WPF.FileProperties |
7 |
{ |
8 |
public static class SizeExtensions |
9 |
{ |
10 |
|
11 |
|
12 |
static readonly string[] SizeSuffixes = { |
13 |
"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; |
14 |
|
15 |
public static string ToByteSize(this long size) |
16 |
{ |
17 |
|
18 |
const string formatTemplate = "{0}{1:0.#} {2}"; |
19 |
|
20 |
if (size == 0) |
21 |
{ |
22 |
return string.Format(formatTemplate, null, 0, SizeSuffixes[0]); |
23 |
} |
24 |
|
25 |
var absSize = Math.Abs((double)size); |
26 |
var fpPower = Math.Log(absSize, 1000); |
27 |
var intPower = (int)fpPower; |
28 |
var iUnit = intPower >= SizeSuffixes.Length |
29 |
? SizeSuffixes.Length - 1 |
30 |
: intPower; |
31 |
var normSize = absSize / Math.Pow(1000, iUnit); |
32 |
|
33 |
return string.Format( |
34 |
formatTemplate, |
35 |
size < 0 ? "-" : null, normSize, SizeSuffixes[iUnit]); |
36 |
} |
37 |
|
38 |
} |
39 |
} |