删除不必要的小数



我得到了从数据库中获取浮点数的代码。

for (int i = 0; i < ingredient.size() ; i++) {
    Ingredient ing = (Ingredient) ingredient.get(i);
    ingredients += String.valueOf(ing.getAmount()) + " " +
                   ing.getUnit() + " " + ing.getIngredient() + "n";
}

数据库以 REAL 值写入,因为其中一些是 1.5、2.5、1.4 等。但是我们也有这些不需要小数的整数,例如 1、4、10 等。问题是数据库表需要具有 REAL 值,这使我们别无选择,只能为所有值指定一个小数,无论是否需要它。

因此,我们最终会得到如下值:1.01.52.320.05,0

我的问题是:我们如何删除不必要的小数,但保留需要它的小数?

删除这些字符的一种非常简单的方法是使用StringUtils去除字符。

String displayValue = String.valueOf(ing.getAmount());
displayValue = StringUtils.stripEnd(displayValue, ".0");

对于输入"1.0","1"将返回

一种更技术性的方法是使用模运算符%

例如:

if(value%1 == 0){  //1 divides into number perfectly, there is no decimal
    //cast value to integer or another non decimal variable
} else {
    //use existing value as it contains a decimal
}

这个怎么样(不需要任何像StringUtils这样花哨的东西)?

    String s = String.valueOf(1.0);
    System.out.println(s);
    /* Make this block as a function and return an int */
    String ss = " ";
    if (s.charAt(s.length()-2) == '.' && s.charAt(s.length()-1) == '0'){
        ss = s.substring(0,s.length()-2);
        System.out.println(ss);
    }
    /**************************************************/
    int converted = Integer.parseInt(ss);
    System.out.println(converted);
}

如果你想让它成为一个功能块,你可以。

您可以在 IDEONE 上检查它的工作 - http://ideone.com/udJv8M

用模检查浮点值。如果返回 0,则它是一个整数。以下是您提到的数字的示例:

    List<Float> values = new ArrayList<Float>();
    values.add(new Float(1.0f));
    values.add(new Float(1.5f));
    values.add(new Float(2.3f));
    values.add(new Float(20.0f));
    values.add(new Float(5.0f));
    List<String> strValues = new ArrayList<String>();
    for(Float value : values)
    {
        String strValue = "";
        if(value % 1 == 0)
        {
            Integer intValue = value.intValue();
            strValue = intValue.toString();
            strValues.add(strValue);
        }
        else
        {
            strValue = value.toString();
            strValues.add(strValue);
        }
        System.out.println(strValue);
    }
您可以使用

自定义DecimalFormat模式:

public static String customFormat(String pattern, double value) {
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    return myFormatter.format(value);
}

然后,#模式定义了可选数字的占位符,因此#.###将仅在必要时放弃最多 3 位数字。

for (int i = 0; i < ingredient.size() ; i++) {
    Ingredient ing = (Ingredient) ingredient.get(i);
    ingredients += customFormat("#.###", ing.getAmount()) +
                   " " + ing.getUnit() + " " + ing.getIngredient() + "n";
}
因此,

除了仅显示之外,不要将数据转换为字符串。 实数可以使用相同的数据类型表示整数和浮点数。 另外,如果你需要对你的数字做任何数学运算,你不能使用字符串来做到这一点。 如果您在将数字存储到成分之前将数字从数据库直接转换为字符串,那么如果您想对这些数字进行计算,那么您以后就搞砸了。 (假设您想添加一个功能以使配方翻倍,并让用户更改所有数量)。 根据你目前的计划,你阻止自己做这样的事情,因为你过于专注于那个数字的显示。

相反,只需在 Ingredient 上创建一个方法来使用 String.format() 转换您的数字。 这样:

 public class Ingredient {
     private double amount;
     private String name;
     public String asDecimal() {
         return String.format("%.1f", amount);
     }
     public String asInteger() {
         return String.format("%.0f", amount);
     }
     public String asFraction() {
         // exercise left to the reader
     }
 }

您甚至可以添加一个将小数转换为小数的函数,以便更轻松地显示酋长可能理解的内容与更难的小数。 请记住,String.format() 将四舍五入浮点数 (0.5 -> 1 作为整数)。

将从 ing.getAmount() 返回的String转换为 Float 对象,然后使用取模函数确定您的值是否是 1 的精确倍数(即没有小数位)。如果是这样,请将Float对象转换为 int ,这将连接小数。

Float f = Float.valueOf(ing.getAmount());
if(f%1 == 0) {
    // Use f.intValue() to concatenate your decimals.
    ingredients +=String.valueOf(f.intValue() + " " + ing.getUnit() + " " + ing.getIngredient() + "n";
}
else {
    ingredients +=String.valueOf(ing.getAmount()) + " " + ing.getUnit() + " " + ing.getIngredient() + "n";
}

我希望这有所帮助。

最新更新