Convert size to XB, XKB, XMB, XGB
    :param size: length value
    :return: string value with size unit
494910
def format_size(size):
    
    units = ['B', 'KB', 'MB', 'GB']
    unit = ''
    n = size
    old_n = n
    value = size
    for i in units:
        old_n = n
        x, y = divmod(n, 1024)
        if x == 0:
            unit = i
            value = y
            break

        n = x
        unit = i
        value = old_n
    return str(value)+unit
664519
protected function convertToBytes($size)
	{
		if(is_numeric($unit = substr($size, -3)) === false)
		{
			$size = substr($size, 0, -3);

			switch($unit)
			{
				case 'KiB':
					return $size * 1024;
				case 'MiB':
					return $size * (1024 ** 2);
				case 'GiB':
					return $size * (1024 ** 3);
				case 'TiB':
					return $size * (1024 ** 4);
				case 'PiB':
					return $size * (1024 ** 5);
				case 'EiB':
					return $size * (1024 ** 6);
				case 'ZiB':
					return $size * (1024 ** 7);
				case 'YiB':
					return $size * (1024 ** 8);
				default:
					throw new RuntimeException(vsprintf('Invalid unit type [ %s ].', [$unit]));
			}
		}

		return (int) $size;
	}
604298
def _readable_part_size(num_bytes):
    ""
    B = num_bytes
    KB = float(1024)
    MB = float(KB * 1024)
    GB = float(MB * 1024)
    TB = float(GB * 1024)

    if B < KB:
        return '{0} {1}'.format(B, 'bytes' if B != 1 else 'byte')
    elif KB <= B < MB:
        return '{0:.2f} KiB'.format(B/KB)
    elif MB <= B < GB:
        return '{0:.2f} MiB'.format(B/MB)
    elif GB <= B < TB:
        return '{0:.2f} GiB'.format(B/GB)
    elif TB <= B:
        return '{0:.2f} TiB'.format(B/TB)
280847
def human_size(size_bytes, precision=0):
    
    if size_bytes == 1:
        # because I really hate unnecessary plurals
        return "1 byte"

    suffixes_table = [('bytes',0),('KB',0),('MB',1),('GB',2),('TB',2), ('PB',2)]

    num = float(size_bytes)
    for suffix, precision in suffixes_table:
        if num < 1024.0:
            break
        num /= 1024.0

    if precision == 0:
        formatted_size = "%d" % num
    else:
        formatted_size = str(round(num, ndigits=precision))

    return "%s %s" % (formatted_size, suffix)
1340088
public static String formatSize( long size )
	{
		if (size == 0)
			return "0";
		
		StringBuilder sb = new StringBuilder();
		if (size < 0)
		{
			size = -size;
			sb.append("-");
		}
	
		long gigs = size / (1024*1024*1024);
		if (gigs > 0)
		{
			sb.append(new DecimalFormat("######.###").format((double)size/(1024*1024*1024)));
			sb.append(" GB");
			return sb.toString();
		}
		
		long megs = size / (1024*1024);
		if (megs > 0)
		{
			sb.append(new DecimalFormat("###.#").format((double)size/(1024*1024)));
			sb.append(" MB");
			return sb.toString();
		}
		
		long kbs = size / (1024);
		if (kbs > 0)
		{
			sb.append(new DecimalFormat("###.#").format((double)size/(1024)));
			sb.append(" KB");
			return sb.toString();
		}
		
		sb.append(size);
		sb.append(" B");
		
		return sb.toString();
	}
1191605
def human_size(s, factor):
    
    unit = 'B'
    if s > factor:
        s /= factor
        unit = 'KB'
    if s > factor:
        s /= factor
        unit = 'MB'
    if s > factor:
        s /= factor
        unit = 'GB'
    if s > factor:
        s /= factor
        unit = 'TB'
    return '%.2f %s' % (s, unit)
52958
def _FormatSizeInUnitsOf1024(self, size):
    
    magnitude_1024 = 0
    used_memory_1024 = float(size)
    while used_memory_1024 >= 1024:
      used_memory_1024 /= 1024
      magnitude_1024 += 1

    if 0 < magnitude_1024 <= 7:
      return '{0:.1f} {1:s}'.format(
          used_memory_1024, self._UNITS_1024[magnitude_1024])

    return '{0:d} B'.format(size)
416506
def free_size(self, units="MiB"):
        
        self.open()
        size = lvm_vg_get_free_size(self.handle)
        self.close()
        return size_convert(size, units)
190342
def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
1009007
def resize_bytes(self, size):
        
        Buffer.resize_bytes(self, size)
        self._size = size // self.itemsize
1250666
def convert_to_kb(unit, size):
    '''
    
    '''
    if unit.lower() == 'gb':
        # vCenter needs long value
        target_size = int(size * 1024 * 1024)
    elif unit.lower() == 'mb':
        target_size = int(size * 1024)
    elif unit.lower() == 'kb':
        target_size = int(size)
    else:
        raise salt.exceptions.ArgumentValueError('The unit is not specified')
    return {'size': target_size, 'unit': 'KB'}
664864
def _size_fmt(num):
    '''
    
    '''
    try:
        num = int(num)
        if num < 1024:
            return '{0} bytes'.format(num)
        num /= 1024.0
        for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
            if num < 1024.0:
                return '{0:3.1f} {1}'.format(num, unit)
            num /= 1024.0
    except Exception:
        log.error('Unable to format file size for \'%s\'', num)
        return 'unknown'
186001
private static int sizeToInt(String size) {
		if (size==null) return -1;
		if ("full".equals(size)) return 12;
		if ("full-size".equals(size)) return 12;
		if ("fullSize".equals(size)) return 12;
		if ("full-width".equals(size)) return 12;
		if ("fullWidth".equals(size)) return 12;
		if ("half".equals(size)) return 6;
		if ("one-third".equals(size)) return 4;
		if ("oneThird".equals(size)) return 4;
		if ("two-thirds".equals(size)) return 8;
		if ("twoThirds".equals(size)) return 8;
		if ("one-fourth".equals(size)) return 3;
		if ("oneFourth".equals(size)) return 3;
		if ("three-fourths".equals(size)) return 9;
		if ("threeFourths".equals(size)) return 9;
		if (size.length()>2) {
			size=size.replace("columns", "");
			size=size.replace("column", "");
			size=size.trim();
		}
		return new Integer(size).intValue();
	}
24786
def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'):
        """"""
        if bytes is None:
            return
        size = float(bytes)
        for unit in C.SIZE_UNITS:
            if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
                return "{size:.{decimals}f}{sep}{unit}{suffix}".format(
                    size=size,
                    unit=unit,
                    suffix=suffix,
                    sep=sep,
                    decimals=C.SIZE_UNITS.index(unit) > 0 and decimals or 0,  # B with no decimal
                )
            size /= 1024
105417
function(size) {
    var match;
    var buffer;
    if (match = size.match(/(\d+)KB/)) {
      buffer = new Buffer(parseInt(match[1]) * 1024);
    } else if (match = size.match(/(\d+)MB/)) {
      buffer = new Buffer(parseInt(match[1]) * 1024 * 1024);
    } else {
      switch (size) {
        case 'empty': buffer = new Buffer(0); break;
        case 'small': buffer = new Buffer(1024 * 1024); break;
        case 'large': buffer = new Buffer(1024 * 1024 * 20); break;
        default: return new Buffer(1024 * 1024);
      }
    }
    buffer.fill('x');
    return buffer;
  }
414354
def __MaxSizeToInt(self, max_size):
        """"""
        size_groups = re.match(r'(?P<size>\d+)(?P<unit>.B)?$', max_size)
        if size_groups is None:
            raise ValueError('Could not parse maxSize')
        size, unit = size_groups.group('size', 'unit')
        shift = 0
        if unit is not None:
            unit_dict = {'KB': 10, 'MB': 20, 'GB': 30, 'TB': 40}
            shift = unit_dict.get(unit.upper())
            if shift is None:
                raise ValueError('Unknown unit %s' % unit)
        return int(size) * (1 << shift)
1062715
def filesizeformat(bytes, decimals=1):
    

    try:
        bytes = float(bytes)
    except (TypeError, ValueError, UnicodeDecodeError):
        raise ValueError

    def filesize_number_format(value):
        return formats.number_format(round(value, decimals), decimals)

    units_list = sorted(six.iteritems(FILESIZE_UNITS), key=operator.itemgetter(1))

    value = unit = None
    len_unints_list = len(units_list)
    for i in xrange(1, len_unints_list):
        if bytes < units_list[i][1]:
            prev_unit = units_list[i - 1]
            value = filesize_number_format(bytes / prev_unit[1])
            unit = prev_unit[0]
            break

    if value is None:
        value = filesize_number_format(bytes / units_list[-1][1])
        unit = units_list[-1][0]

    return SIZEFIELD_FORMAT.format(value=value, unit=unit)