将KB动态转换为MB,GB,TB [英] Converting KB to MB, GB, TB dynamically

查看:202
本文介绍了将KB动态转换为MB,GB,TB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public String size(int size){
String hrSize =;
int k = size;
double m = size / 1024;
double g = size / 1048576;
double t = size / 1073741824;

DecimalFormat dec = new DecimalFormat(0.00);

if(k> 0)
{

hrSize = dec.format(k).concat(KB);

}
if(m> 0)
{

hrSize = dec.format(m).concat(MB);
}
if(g> 0)
{

hrSize = dec.format(g).concat(GB);
}
if(t> 0)
{

hrSize = dec.format(t).concat(TB);
}

return hrSize;
}

这是一种应该以GB,MB,KB或TB返回大小的方法。输入值为KB。
例如,结果为1245应为1.21MB,但我得到的是1.00MB。

解决方案

整数除法。所以除法的结果也是 integer 。小数部分被截断。

 所以,1245/1024 = 1 
pre>

将您的部门更改为浮点分区: -

  double m = size / 1024.0; 
double g = size / 1048576.0;
double t = size / 1073741824.0;

此外,您的比较是错误的。您应该与 1 进行比较。

  if(m> 1)if if(t> 1)if(g> 1)

理想情况下,我会更改您的比较: -

  if(t> 1){
hrSize = dec.format(t).concat(TB);
} else if(g> 1){
hrSize = dec.format(g).concat(GB);
} else if(m> 1){
hrSize = dec.format(m).concat(MB);
} else {
hrSize = dec.format(size).concat(KB);
}

您需要先与较高单位进行比较,然后移至较低位置一个。


public String size(int size){
    String hrSize = "";
    int k = size;
    double m = size/1024;
    double g = size/1048576;
    double t = size/1073741824;

    DecimalFormat dec = new DecimalFormat("0.00");

    if (k>0)
    {

        hrSize = dec.format(k).concat("KB");

    }
    if (m>0)
    {

        hrSize = dec.format(m).concat("MB");
    }
    if (g>0)
    {

        hrSize = dec.format(g).concat("GB");
    }
    if (t>0)
    {

        hrSize = dec.format(t).concat("TB");
    }

    return hrSize;
    }

This is a method that should return size in GB,MB, KB or TB. Input value is in KB. for example result for 1245 should be like 1.21MB but what I get is 1.00MB.

解决方案

You are performing integer division. So the result of division is also integer. And fractional part is truncated.

so, 1245 / 1024 = 1

Change your division to floating point division: -

double m = size/1024.0;
double g = size/1048576.0;
double t = size/1073741824.0;

Also, your comparison is faulty. You should do the comparison with 1.

if (m > 1), if (t > 1), if (g > 1)

Ideally I would change your comparison to: -

    if (t > 1) {
        hrSize = dec.format(t).concat("TB");
    } else if (g > 1) {
        hrSize = dec.format(g).concat("GB");
    } else if (m > 1) {
        hrSize = dec.format(m).concat("MB");
    } else {
        hrSize = dec.format(size).concat("KB");
    }

You need to compare with the higher unit first, and then move to the lower one.

这篇关于将KB动态转换为MB,GB,TB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆