Bytes to Human Readable Size

Medium Numbers
Convert a byte count into a human-readable size (B, KB, MB, GB) — handy for showing file/download sizes in an app.

Sample input

1536

Sample output

1.5 KB

Solution

def human_readable(size):
    units = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    value = float(size)
    while value >= 1024 and i < len(units) - 1:
        value /= 1024
        i += 1
    return f"{value:.1f} {units[i]}"

print(human_readable(1536))
function humanReadable(size) {
  const units = ["B", "KB", "MB", "GB", "TB"];
  let i = 0, value = size;
  while (value >= 1024 && i < units.length - 1) {
    value /= 1024;
    i++;
  }
  return value.toFixed(1) + " " + units[i];
}

console.log(humanReadable(1536));
import java.util.Locale;

public class Main {
    static String humanReadable(long size) {
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int i = 0;
        double value = size;
        while (value >= 1024 && i < units.length - 1) {
            value /= 1024;
            i++;
        }
        return String.format(Locale.US, "%.1f %s", value, units[i]);
    }

    public static void main(String[] args) {
        System.out.println(humanReadable(1536));
    }
}
import java.util.Locale

fun humanReadable(size: Long): String {
    val units = listOf("B", "KB", "MB", "GB", "TB")
    var i = 0
    var value = size.toDouble()
    while (value >= 1024 && i < units.size - 1) {
        value /= 1024
        i++
    }
    return String.format(Locale.US, "%.1f %s", value, units[i])
}

fun main() {
    println(humanReadable(1536))
}
import Foundation

func humanReadable(_ size: Int) -> String {
    let units = ["B", "KB", "MB", "GB", "TB"]
    var i = 0
    var value = Double(size)
    while value >= 1024 && i < units.count - 1 {
        value /= 1024
        i += 1
    }
    return String(format: "%.1f %@", value, units[i])
}

print(humanReadable(1536))
String humanReadable(int size) {
  final units = ['B', 'KB', 'MB', 'GB', 'TB'];
  var i = 0;
  var value = size.toDouble();
  while (value >= 1024 && i < units.length - 1) {
    value /= 1024;
    i++;
  }
  return '${value.toStringAsFixed(1)} ${units[i]}';
}

void main() {
  print(humanReadable(1536));
}
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;

string humanReadable(long size) {
    const char* units[] = {"B", "KB", "MB", "GB", "TB"};
    int i = 0;
    double value = size;
    while (value >= 1024 && i < 4) {
        value /= 1024;
        i++;
    }
    char buf[64];
    snprintf(buf, sizeof(buf), "%.1f %s", value, units[i]);
    return string(buf);
}

int main() {
    cout << humanReadable(1536) << endl;
    return 0;
}
#include <stdio.h>

int main() {
    long size = 1536;
    const char* units[] = {"B", "KB", "MB", "GB", "TB"};
    int i = 0;
    double value = size;
    while (value >= 1024 && i < 4) {
        value /= 1024;
        i++;
    }
    printf("%.1f %s\n", value, units[i]);
    return 0;
}