简体   繁体   English

Groovy - java 多个同时转换

[英]Groovy - java multiple conversions at the same time

I would like to know if someone has tips on how to convert KB's variables all at the same time.我想知道是否有人有关于如何同时转换 KB 变量的提示。

I'm reaching a Linux remote machine and retrieving at the same time 3 variables:我正在访问 Linux 远程机器并同时检索 3 个变量:

They are: Memory RAM total, Memory RAM used, and Memory RAM available.它们是:Memory RAM 总计,Memory RAM 已使用,Memory RAM 可用。 The variables are received in KB's "format" but I need to display them in Gigabytes.(See the example below)变量以 KB 的“格式”接收,但我需要以千兆字节显示它们。(参见下面的示例)

I can convert them all but only one at a time and the idea is to convert them all at the same time.我可以一次转换它们,但一次只能转换一个,我的想法是同时转换它们。

Memory RAM total: 5000000      // KB
Memory RAM used: 2000000       // KB
Memory RAM available: 3000000  //KB

This is what I did so far to convert only the Memory RAM total variable.这是我到目前为止所做的仅转换 Memory RAM 总变量。

def size = 5000000 // Memory that can be converted KB MB GB AND TERABYTE

String hrSize = ""

try {
    int k = size
    double m = size / 1024 // bytes
    double g = size / 1048576 // bytes
    double t = size / 1073741824 // bytes

    DecimalFormat dec = new DecimalFormat("0.00")

    if (k > 1) {
      //If the size is more than 1kb but less than 1024 bytes, the output will be KiloBytes
        hrSize = dec.format(k).concat("KB")
    }
    if (m > 1) {
      //If the size is more than 1kb but less than 1048576 bytes, the output will be Megabytes
        hrSize = dec.format(m).concat("MB")
    }
    if (g > 1) {
      //If the size is more than 1kb and more than 1048576 but less than 1073741824 bytes, the output will be Gigabytes
        hrSize = dec.format(g).concat("GB")
    }
    if (t > 1) {
      //If the size is more than 1073741824 bytes the output will be Terabytes.
        hrSize = dec.format(t).concat("TB")
    }
} catch (Exception e) {
    println("This program ran into a problem, root cause" + e)

}
println(" The total memory from this computer is: " + hrSize)

Output: Output:

The total memory from this computer is: 4,77GB

What I'm looking for?我在找什么?

The total memory from this computer is: 4,77GB
The total free from this computer is: 1,91GB
The total Available from this computer is: 2,86GB

Any documentation or tips?任何文档或提示?

You can improve the function by making it a loop您可以通过使其成为循环来改进 function

def prettySize(float size) {
    def label = ['b', 'KB', 'MB', 'GB', 'TB'].find {
        if( size < 1024 ) {
            true
        } else {
            size /= 1024 
            false
        }
    }
    "${new java.text.DecimalFormat('0.##').format(size)}$label"
}

println("The total memory from this computer is: ${prettySize(size)}")

Prints:印刷:

The total memory from this computer is: 4.77MB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM