Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round float number in Android

I am stuck in the scenario below:

If x is 1.5 or lower then the final result will be x = 1. If x is large than 1.5 then x = 2.

The input number will be x/100.

For instance: input = 0.015 => x = 1.5 => display x = 1.

The problem I got is that float number is inaccurate. For example: input = 0.015 but actually it is something like 0.01500000000000002. In this case, x gonna be 1.500000000000002 which is large than 1.5 => display output is x = 2.

It happen so randomly which I don't know how to solve it. Like 0.5, 1.5 will give me the correct result. But 2.5, 3.5, 4.5, 5.5 will give me the wrong result. Then 6.5 will give me the correct result again.

The code I implemented is below:

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

So depends on x, the output might be right or wrong. It is just so random.

I alos tried to use Math.round, Math.floor, Math.ceils but none of them seems work since float number is so unpredictable.

Any suggestion for the solution?

Thanks in advance.

like image 951
Long Dao Avatar asked Aug 22 '16 11:08

Long Dao


3 Answers

I like simple answers,

Math.round(1.6); // Output:- 2
Math.round(1.5); // Output:- 2
Math.round(1.4); // Output:- 1
like image 115
Rishi Swethan Avatar answered Sep 20 '22 06:09

Rishi Swethan


to round a float value f to 2 decimal places.

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

to convert String to float...

float number = Float.valueOf(s)

if want to round float to int then.... there are different ways to downcast float to int, depending on the result you want to achieve.

round (the closest integer to given float)

int i = Math.round(f);

example

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

like image 40
Jitesh Prajapati Avatar answered Sep 19 '22 06:09

Jitesh Prajapati


You could use String.format.

String s = String.format("%.2f", 1.2975118);
like image 32
MurugananthamS Avatar answered Sep 18 '22 06:09

MurugananthamS