如何在Android中舍入浮点数

时间:2016-08-22 11:46:20

标签: java android double decimal rounding

我陷入了下面的情景:

如果x为1.5或更低,则最终结果为x = 1。 如果x大于1.5则x = 2。

输入数字为x / 100.

例如: input = 0.015 => x = 1.5 =>显示x = 1。

我得到的问题是浮点数不准确。例如: input = 0.015但实际上它是0.01500000000000002。在这种情况下,x将是1.500000000000002,其大于1.5 =>显示输出为x = 2。

它是随机发生的,我不知道如何解决它。像0.5一样,1.5会给我正确的结果。但2.5,3.5,4.5,5.5会给我错误的结果。然后6.5会再次给我正确的结果。

我实施的代码如下:

float x = 0.015;
NumberFormat nf = DecimalFormat.getPercentInstance();
nf.setMaximumFractionDigits(0);
output = nf.format(x);

因此取决于x,输出可能是对还是错。它是随机的。

我尝试使用Math.round,Math.floor,Math.ceils,但由于浮点数无法预测,所以它们似乎都不起作用。

对解决方案的任何建议?

提前致谢。

5 个答案:

答案 0 :(得分:4)

您可以使用String.format

String s = String.format("%.2f", 1.2975118);

答案 1 :(得分:3)

float值f舍入到2位小数。

String s = String.format("%.2f", f);

String转换为float ...

float number = Float.valueOf(s)

如果想将float舍入到int那么.... 有不同的方法可以将float向下转换为int,具体取决于你想要实现的结果。

round(给定float的最接近整数)

int i = Math.round(f);

例如

  

f = 2.0 - > i = 2; f = 2.22 - > i = 2; f = 2.68 - > i = 3
  f = -2.0 - > i = -2; f = -2.22 - > i = -2; f = -2.68 - > i = -3

答案 2 :(得分:1)

这是我的旧代码高尔夫答案。

public class Main {

    public static void main(String[] args) {
        System.out.println(math(1.5f));
        System.out.println(math(1.500001f));
        System.out.println(math(1.49999f));
    }

    public static int math(float f) {
        int c = (int) ((f) + 0.5f);
        float n = f + 0.5f;
        return (n - c) % 2 == 0 ? (int) f : c;
    }

}

输出:

1
2
1

答案 3 :(得分:0)

我遇到了同样的问题,我使用了DecimalFormat。这可能会对你有所帮助。

float x = 1.500000000000002f;
DecimalFormat df = new DecimalFormat("###.######");
long l = df.format(x);
System.out.println("Value of l:"+l);

答案 4 :(得分:0)

我喜欢简单的答案,

Math.round(1.6); // Output:- 2
Math.round(1.5); // Output:- 2
Math.round(1.4); // Output:- 1