Convert to Kb, Mb ... - CSharp System

CSharp examples for System:String Convert

Description

Convert to Kb, Mb ...

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System;//from  w w w .j a va 2s.  c o m
using Microsoft.VisualBasic.CompilerServices;

public class Main{
        /// <summary>
        /// Convert to Kb, Mb ...
        /// </summary>
        /// <param name="bytes">Bytes to convert</param>
        public static string Convert2KbWithBytes(long bytes)
        {
            if (bytes < 1024) return bytes.ToString() + " b";
            return bytes.ToString() + " b -> " + StringHelper.Convert2Kb(bytes);
        }
        /// <summary>
        /// Convert to Kb, Mb ...
        /// </summary>
        /// <param name="bytes">Bytes to convert</param>
        public static string Convert2Kb(long bytes)
        {
            if (bytes < 1024) return bytes.ToString() + " b";
            if (bytes < 1024 * 1024) return (bytes / (1024.0)).ToString("0.00") + " Kb";
            if (bytes < 1024 * 1024 * 1024) return (bytes / (1024.0 * 1024.0)).ToString("0.00") + " Mb";
            if (bytes < 1024 * 1024 * 1024 * 1024.0) return (bytes / (1024.0 * 1024.0 * 1024.0)).ToString("0.00") + " Gb";
            return (bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0)).ToString("0.00") + " Tb";
        }
        /// <summary>
        /// Convert to Kb, Mb ...
        /// </summary>
        /// <param name="bytes">Bytes to convert</param>
        public static string Convert2Kb(double bytes) { return Convert2Kb((long)bytes); }
}

Related Tutorials