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,895 questions

51,826 answers

573 users

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

1 Answer

0 votes
object FormatBytesToKilobytesMegabytesGigabytesTerabytes_Scala {
  def main(args: Array[String]): Unit = {
    println(formatBytes(9823453784599L))
    println(formatBytes(7124362542L))
    println(formatBytes(23746178))
    println(formatBytes(1048576))
    println(formatBytes(1024000))
    println(formatBytes(873445))
    println(formatBytes(1024))
    println(formatBytes(978))
    println(formatBytes(13))
    println(formatBytes(0))
  }

  def formatBytes(bytes: Long): String = {
    val sizes = Array("B", "KB", "MB", "GB", "TB")
    var i = 0
    var dblByte = bytes.toDouble
    var tempBytes = bytes

    while (i < sizes.length && tempBytes >= 1024) {
      dblByte = tempBytes / 1024.0
      tempBytes /= 1024
      i += 1
    }

    f"$dblByte%.2f ${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
...