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

1.3k Views Asked by At

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;
    }
3

There are 3 best solutions below

5
On BEST ANSWER

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.

0
On

20.26496724167345 isn't a huge number. It's just over 20. It's a long textual representation, but that's a different matter.

You need to look at where you're displaying the number. For example, you might want to use:

Console.WriteLine("{0:0.##}MB", value);

Or

Console.WriteLine("{0:F2}MB", value);

See custom numeric format strings and standard numeric format strings for more details.

2
On

for using it in display you can always use String.Format method as in:

string mb = String.Format("{0:F2}MB", B2MB(bytes));

for just rounding it down you can use

Math.Round((bytes / 1024f) / 1024f, 2);