pretty_bytes/
converter.rs

1use std::cmp;
2
3pub fn convert(num: f64) -> String {
4  let negative = if num.is_sign_positive() { "" } else { "-" };
5  let num = num.abs();
6  let units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
7  if num < 1_f64 {
8      return format!("{}{} {}", negative, num, "B");
9  }
10  let delimiter = 1000_f64;
11  let exponent = cmp::min((num.ln() / delimiter.ln()).floor() as i32, (units.len() - 1) as i32);
12  let pretty_bytes = format!("{:.2}", num / delimiter.powi(exponent)).parse::<f64>().unwrap() * 1_f64;
13  let unit = units[exponent as usize];
14  format!("{}{} {}", negative, pretty_bytes, unit)
15}