简体   繁体   English

Java将浮点数转换为整数

[英]Java convert float to integer

I want to do an operation like this : if the given float numbers are like 1.0 , 2.0 , 3.0 , I want to save them to database as integer (1,2,3 ), if they are like 1.1 , 2.1 , ,3.44 , I save them as float.我想做这样的操作:如果给定的浮点数像 1.0 、 2.0 、 3.0 ,我想将它们作为整数 (1,2,3 ) 保存到数据库中,如果它们像 1.1 、 2.1 、 ,3.44 ,我将它们保存为浮动。 what's the best solution for this problem using java ?使用 java 解决此问题的最佳解决方案是什么? The corresponding field in database is type of varchar.数据库中对应的字段为varchar类型。

Just try int i = (int) f;试试int i = (int) f; . .

EDIT : I see the point in the question.编辑:我看到了问题的重点。 This code might work :此代码可能有效:

 int i = (int) f;
 String valToStore = (i == f) ? String.valueOf(i) : String.valueOf(f);
String result = "0";
if (floatVar == Math.floor(floatVar)) {
    result = Integer.toString((int) floatVar);
} else {
    result = Float.toString(floatVar);
}

The if-clause checks whether the number is a whole number - ie if it is equal to the result of rounding it down to the closest whole value. if 子句检查数字是否为整数 - 即它是否等于将其向下舍入到最接近的整数值的结果。

But this is very odd requirement indeed, and perhaps you should reconsider the need for such a thing.但这确实是非常奇怪的要求,也许您应该重新考虑是否需要这样的东西。

Seems like you want to save Floats with no trailing numbers as Integers, while saving those with significant trailing numbers as Floats.似乎您想将没有尾随数字的浮点数保存为整数,同时将具有重要尾随数字的浮点数保存为浮点数。 I would rather just save it all as Float to the DB, but it's your question so here's my answer:我宁愿将其全部保存为 Float 到数据库,但这是您的问题,所以这是我的答案:

/**
   * Method to determine if trailing numbers are significant or not. Significant
   * here means larger than 0
   * 
   * @param fFloat
   * @return
   */
  public static boolean isTrailingSignificant(Float fFloat)
  {
    int iConvertedFloat = fFloat.intValue();// this drops trailing numbers
    // checks if difference is 0
    return ((fFloat - iConvertedFloat) > 0);
  }

This is how you would use this method:这是您将如何使用此方法:

 Number oNumToSave = null;
if (isTrailingSignificant(fFloat))
{
  // save float value as is
  oNumToSave = fFloat;
}
else
{
  // save as int
  oNumToSave = fFloat.intValue();// drops trailing numbers      
}

After that, you can do the database operation using the variable oNumToSave.之后,您可以使用变量 oNumToSave 进行数据库操作。

Not sure this is the best solution, but you can try to write a method like this :不确定这是最好的解决方案,但您可以尝试编写这样的方法:

String convertToString(Float f) {
  if (f.toString().endsWith(".0"))
      return f.intValue().toString();
  else
      return f.toString();
}

Kotlin:科特林:

    val mAmount = 3.0
    val intAmount = mAmount.toInt()
    val amountToDisplay = if (intAmount.compareTo(mAmount) == 0) intAmount.toString() else java.lang.String.valueOf(mAmount)

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

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