Search code examples
c#doublebytemegabyte

C# How do I shorten my double when I converted bytes to megabytes?


Hello I made a updater that downloads update files but I always used bytes as indication now
I found a way to convert it to megabytes,

it works good but one little problem it returns HUGE numbers for example,
a file that is 20MB will be displayed as : 20.26496724167345 MB

How do I make this number a bit shorter like 20.26MB

This is the code that converts it to mb :

    static double B2MB(long bytes)
    {
        return (bytes / 1024f) / 1024f;
    }

Solution

  • You can use Math.round to round to a specified number of digits. If you want two, as in this case, you use it like so: Math.Round(inputValue, 2);. Your code would look something like this:

    static double B2MB(long bytes)
    {
        return Math.Round((bytes / 1024f) / 1024f, 2);
    }
    

    NOTE: Because floating point numbers don't have infinite precision, this may result in something like 24.24999999999999999 instead of 24.25. This method is worth knowing, but if you're outputting it as a string, you should look at using formatting strings, as the other answers do.