Skip to content

Instantly share code, notes, and snippets.

@SajjadArifGul
Created October 9, 2015 13:08
Show Gist options
  • Save SajjadArifGul/652fd3bdf2d9d9dced15 to your computer and use it in GitHub Desktop.
Save SajjadArifGul/652fd3bdf2d9d9dced15 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConvertBytesToKB_MB_GB_TBinCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ConvertButton_Click(object sender, EventArgs e)
{
double Value = Convert.ToDouble(ValueBox.Text);
ResultBox.Text = (ToFileSize(Value)).ToString();
}
public static string ToFileSize(double value)
{
string[] suffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
for (int i = 0; i < suffixes.Length; i++)
{
if (value <= (Math.Pow(1024, i + 1)))
{
return ThreeNonZeroDigits(value / Math.Pow(1024, i)) + " " + suffixes[i];
}
}
return ThreeNonZeroDigits(value / Math.Pow(1024, suffixes.Length - 1)) +
" " + suffixes[suffixes.Length - 1];
}
// Return the value formatted to include at most three
// non-zero digits and at most two digits after the
// decimal point. Examples:
// 1
// 123
// 12.3
// 1.23
// 0.12
private static string ThreeNonZeroDigits(double value)
{
if (value >= 100)
{
// No digits after the decimal.
return value.ToString("0,0");
}
else if (value >= 10)
{
// One digit after the decimal.
return value.ToString("0.0");
}
else
{
// Two digits after the decimal.
return value.ToString("0.00");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment