Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

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
...