如何舍入 Android 中的浮点数

How to round float number in Android

我被困在下面的场景中:

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

输入的数字将为x/100。

例如: 输入 = 0.015 => x = 1.5 => 显示 x = 1.

我遇到的问题是浮点数不准确。例如: 输入 = 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,但其中 none 似乎可行,因为浮点数是如此不可预测。

对解决方案有什么建议吗?

提前致谢。

你可以使用 String.format.

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

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

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

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

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

float 值 f 舍入到小数点后两位。

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

String转换为float...

float number = Float.valueOf(s)

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

round(最接近给定浮点数的整数)

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

我喜欢简单的答案,

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