0

I have found this code from a user on a different question but I cannot figure out how to get arguments into those methods (I'm new)

    public static class Ext
{
    private const long OneKb = 1024;
    private const long OneMb = OneKb * 1024;
    private const long OneGb = OneMb * 1024;
    private const long OneTb = OneGb * 1024;

    public static string ToPrettySize(this int value, int decimalPlaces = 0)
    {
        return ((long)value).ToPrettySize(decimalPlaces);
    }

    public static string ToPrettySize(this long value, int decimalPlaces = 0)
    {
        var asTb = Math.Round((double)value / OneTb, decimalPlaces);
        var asGb = Math.Round((double)value / OneGb, decimalPlaces);
        var asMb = Math.Round((double)value / OneMb, decimalPlaces);
        var asKb = Math.Round((double)value / OneKb, decimalPlaces);
        string chosenValue = asTb > 1 ? string.Format("{0}Tb",asTb)
            : asGb > 1 ? string.Format("{0}Gb",asGb)
            : asMb > 1 ? string.Format("{0}Mb",asMb)
            : asKb > 1 ? string.Format("{0}Kb",asKb)
            : string.Format("{0}B", Math.Round((double)value, decimalPlaces));
        return chosenValue;
    }
}

(Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?)

I need to make a calculator which will convert bits into megabits and all other up to Petabytes also Petabytes into bits. Inside a c# console application. And display the calculation to the user.

Community
  • 1
  • 1
Dominik N
  • 3
  • 3
  • With this method you just have to get the size ( in bytes ) like `meFile.Length` and invoke this method. Which can be done in two ways. **first** add `using namespace;` on top of the file and just call `meFile.Length.ToPrettySize(2);` **second** omit the `using` part and just call `Ext.ToPrettySize(meFile.Length, 2)` – mrogal.ski Nov 24 '16 at 15:44

1 Answers1

0

There is only one overloaded method, ToPrettySize(). Just pass in a number and the number of desired decimal places.

Console.WriteLine(Ext.ToPrettySize(1024000, 2)); // 1000Kb
Dan Wilson
  • 3,937
  • 2
  • 17
  • 27
  • That works good, would giving the user the ability to choose what unit hes inputting and what unit output he wants work with this? – Dominik N Nov 24 '16 at 15:51
  • This is method is designed to set the unit for you, although you could modify it to specify the desired unit. – Dan Wilson Nov 24 '16 at 15:56