如何在Android中舍入浮点数

问题描述 投票:5回答:5

我陷入了下面的情景:

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

输入数字为x / 100。

例如:input = 0.015 => x = 1.5 => display 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.ceil但是它们似乎都没有用,因为浮点数是如此不可预测。

对解决方案有何建议?

提前致谢。

java android double decimal rounding
5个回答
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

4
投票

你可以使用String.format

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

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


0
投票

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

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

0
投票

我喜欢简单的答案,

Math.round(1.6); // Output:- 2
Math.round(1.5); // Output:- 2
Math.round(1.4); // Output:- 1
© www.soinside.com 2019 - 2024. All rights reserved.