Take the 2-minute tour ×

Because some people apparently think that gigabytes as a decimal is a good way to accurately store available storage space I now have the following code to convert it into a byte representation:

Convert.ToString(Convert.ToInt64(Math.Floor(someDecimal * 1024 * 1024)));

Now while this works (as-in returns the expected result), it's not exactly elegant.

Is there a more elegant way to do this kind of conversion? (The floor is necessary).

share|improve this question
1024^2 is for Megabytes, not Gigabytes. –  Adam Matan Nov 6 '12 at 8:45
This will give you the kilo-byte representation if someDecimal really contains GB. –  Daniel Hilgarth Nov 6 '12 at 8:45
Why the Math.Floor? –  Rik Nov 6 '12 at 8:51
You guys are right about the kilobyte thing. Thanks. Don't sleep while coding I guess. Rik: Because rounding up (Which I understand Convert.ToInt64 does) could have really bad side effects, so erring on the side of caution. :) –  Mikkel Løkke Nov 6 '12 at 12:09

3 Answers 3

up vote 5 down vote accepted

Why don't you just use this:

var result = ((Int64)(someDecimal * 1024 * 1024 * 1024)).ToString();

Of course, that should be encapsulated in some helper method. you don't want that sprinkled throughout your code.

share|improve this answer
You might want to use a long though –  lc. Nov 6 '12 at 8:48
@lc: Yes, you are right about that. Fixed, thanks. –  Daniel Hilgarth Nov 6 '12 at 8:49
Because I wasn't sure whether explicit casting would round up or truncate? Also didn't know Math.Pow, or whether mulitplying by a constant would have significant performance gain? I'm open to suggestions. –  Mikkel Løkke Nov 6 '12 at 12:12
@Fuex: That edit is not valid. I posted something else! You didn't improve the code, you made it potentially slow. Never ever make such changes in an edit! –  Daniel Hilgarth Nov 6 '12 at 13:31
@MikkelLøkke: I wouldn't use Math.Pow for this task as it is potentially slower. I would use a constant, either inline as in my example or declared in some constant holder class. –  Daniel Hilgarth Nov 6 '12 at 13:33


(someDecimal * Math.Pow(1024,3) - 0.5m).ToString("F0")
share|improve this answer

Consider moving this line to a separate method (say, gigabytesToBytes(someDecimal)). This will make your intention clearer, and if you find bugs - like those spotted in the comments - you could fix them in one place.

share|improve this answer
Thanks, I already have, although I admit your suggestion for method name is better than the "whatTheHellIsWrongWithYou(someDecimal)" that I have now. :) –  Mikkel Løkke Nov 6 '12 at 12:14

Your Answer


