Click to See Complete Forum and Search --> : round up float?


atakado
12-19-2008, 01:17 PM
hi everyone.

I have searched the forum for an answer but couldn't find any.

Is there a simple way to round up float so instead of getting 3,49875985 as a result I would get 3,5? or is there any other way to round up numbers like that without the float?

thanks in advance.

javawebdog
12-19-2008, 01:24 PM
Built in function in Java API -
http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/math/RoundingMode.html
http://java.sun.com/j2se/1.4.2/docs/api/

Check the Method Summary.
example

public class RoundTwoDecimalPlaces{
public static void main(String[] args) {
float num = 2.954165f;
float round = Round(num,2);
System.out.println("Rounded data: " + round);
}

public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}

example
src: http://www.roseindia.net/java/beginners/RoundTwoDecimalPlaces.shtml

atakado
12-20-2008, 02:38 PM
thanks for your help :)

I got another question though :P.

is it possible to convert float to int?

chazzy
12-20-2008, 02:49 PM
is it possible to convert float to int?

All primitive types are interchangeable. you just need to cast

float f = (float)your_int;

but it does it without rounding.

atakado
12-20-2008, 02:56 PM
thanks :)

chazzy
12-21-2008, 10:24 AM
the loss of precision is normal, and you should make note of it since int's are only whole numbers.