public class ByteConversion | |
{ | |
/// | |
/// Converts your number from the specified fromUnit to the toUnit | |
/// | |
///Number to convert | |
///ByteUnit that the number is already in. | |
///ByteUnit that you want to convert your number too. | |
/// | |
public static double Convert(double number, ByteUnit fromUnit, ByteUnit toUnit) | |
{ | |
int difference = (int)fromUnit - (int)toUnit; | |
if (difference < 0) | |
{ | |
return number / Math.Pow(1024, Math.Abs(difference)); | |
} | |
else if (difference > 0) | |
{ | |
return number * Math.Pow(1024, difference); | |
} | |
else //These are the same unit | |
{ | |
return number; | |
} | |
} | |
/// | |
/// Converts the specified number to the closest unit based on size and formats as text. | |
/// | |
///Number to convert | |
///ByteUnit that the number is already in. | |
///ByteUnit that you want to convert your number too. | |
///Separator text between the number and the unit designator (default = " ") | |
/// | |
public static string GetString(double number, ByteUnit fromUnit, string separator = " ") | |
{ | |
var numberInBytes = Convert(number, fromUnit, ByteUnit.Byte); | |
ByteUnit toUnit = fromUnit; | |
foreach (ByteUnit unit in Enum.GetValues(typeof(ByteUnit))) | |
{ | |
double multiplier = 0; | |
int unitMultiplier = (int)unit; | |
if (unitMultiplier > 0) | |
{ | |
multiplier = Math.Pow(1024, unitMultiplier); | |
} | |
var result = numberInBytes / multiplier; | |
if (result < 1024) | |
{ | |
toUnit = unit; | |
break; | |
} | |
} | |
return GetString(number, fromUnit, toUnit, separator); | |
} | |
/// | |
/// Converts the specified number to the unit provided and formats as text. | |
/// | |
///Number to convert | |
///ByteUnit that the number is already in. | |
///ByteUnit that you want to convert your number too. | |
///Separator text between the number and the unit designator (default = " ") | |
/// | |
public static string GetString(double number, ByteUnit fromUnit, ByteUnit toUnit, string separator = " ") | |
{ | |
var convertedNumber = Convert(number, fromUnit, toUnit); | |
return String.Format("{0}{1}{2}", convertedNumber, separator, toUnit.GetDescription()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment