How to round down or up to the nearest decimal value?
Hi, Im quite new to java ^^
Would like to ask how to round down or up a double or float decimal value?
I was trying to display a cosine table using a for loop to display but the values that it added exceeded my upperlimit so the last result wont be displayed.
for(c = lowerl; c <= upperl; c = c + interval)
{
cosvalue = Math.cos(c);
System.out.println("cos(" + c + ") = " + cosvalue);
}
[438 byte] By [
baijiazia] at [2007-11-26 22:50:07]

# 2
Hi I did a try with the 2 methods you said.
public static void main(String[] args)
{
double a, value, value2,value3;
value = Math.sin(90);
value2 = Math.floor(value);
value3 = Math.ceil(value);
System.out.println(value);
System.out.println(value2);
System.out.println(value3);
}
The results are
0.8939966636005579
0.0
1.0
But I needed the to have around 1 - 2 decimal points, these 2 methods rounded off to the nearest integer value =(
# 3
> ...
> But I needed the to have around 1 - 2 decimal points,
> these 2 methods rounded off to the nearest integer
> value =(
Be inventive:
public class Main {
public static void main(String[] args) {
double d = 0.55555555;
System.out.println(myCeil(d, 2));
}
public static double myCeil(double value, int precision) {
double multiply = Math.pow(10, precision);
return Math.ceil(value*multiply)/multiply;
}
}
But why not keep your doubles as precise as possible, and only display them with a certain precision:public class Main {
public static void main(String[] args) {
java.text.NumberFormat nf = new java.text.DecimalFormat("0.00");
double d = 0.55555555;
System.out.println(nf.format(d));
}
}
# 6
value3 = Math.ceil(value*100)/100This works only when you do not need high precision for the double numbers. If you do, read first about properties of floating-point arithmetic in java ( http://forum.java.sun.com/thread.jspa?threadID=676036)
# 7
> value3 = Math.ceil(value*100)/100
>
> This works only when you do not need high precision
> for the double numbers. If you do, read first about
> properties of floating-point arithmetic in java
> (http://forum.java.sun.com/thread.jspa?threadID=676036
Did you not read the replies already given?