git.iko.soy/parseable-android
on icon help sign in
30 lines 1.0 kB history raw
1package com.parseable.android.data
3import java.util.Locale
5private val BYTE_UNITS = arrayOf("B", "KB", "MB", "GB", "TB", "PB")
7/**
8 * Converts a raw byte-count string (e.g. "123456789") to a human-readable
9 * size (e.g. "117.7 MB"). If the string is not a valid number, it is
10 * returned unchanged so pre-formatted values from the API pass through.
11 */
12fun formatBytes(raw: String?): String? {
13 if (raw == null) return null
14 val bytes = raw.trim().toDoubleOrNull() ?: return raw
15 if (bytes < 0) return raw
16 if (bytes < 1024) return String.format(Locale.US, "%.0f B", bytes)
17 var value = bytes
18 var unitIndex = 0
19 while (value >= 1024 && unitIndex < BYTE_UNITS.size - 1) {
20 value /= 1024
21 unitIndex++
22 }
23 return if (value >= 100) {
24 String.format(Locale.US, "%.0f %s", value, BYTE_UNITS[unitIndex])
25 } else if (value >= 10) {
26 String.format(Locale.US, "%.1f %s", value, BYTE_UNITS[unitIndex])
27 } else {
28 String.format(Locale.US, "%.2f %s", value, BYTE_UNITS[unitIndex])
29 }