How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Rust

1 Answer

0 votes
fn main() {
    println!("{}", format_bytes(9823453784599));
    println!("{}", format_bytes(7124362542));
    println!("{}", format_bytes(23746178));
    println!("{}", format_bytes(1048576));
    println!("{}", format_bytes(1024000));
    println!("{}", format_bytes(873445));
    println!("{}", format_bytes(1024));
    println!("{}", format_bytes(978));
    println!("{}", format_bytes(13));
    println!("{}", format_bytes(0));
}

fn format_bytes(bytes: u64) -> String {
    let sizes = ["B", "KB", "MB", "GB", "TB"];
    let mut i = 0;
    let mut dbl_byte = bytes as f64;
    let mut bytes = bytes;

    while i < sizes.len() && bytes >= 1024 {
        dbl_byte = bytes as f64 / 1024.0;
        bytes /= 1024;
        i += 1;
    }

    format!("{:.2} {}", dbl_byte, sizes[i])
}



  
/*
run:

8.93 TB
6.63 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0.00 B
  
*/

 



answered Aug 28, 2024 by avibootz
...