use:
double x=0.555;
System.out.println(Math.round(x));
to round a double easily.
teo236
Junior Poster in Training
73 posts since Jul 2011
Reputation Points: 20
Solved Threads: 10
Or see the String class's format() method.
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
Do you want to round the value in the result?
Vs rounding the value when it is printed?
For example if result = 1.555543
Do you want to change the contents of result to 1.560000?
or leave the value in result unchanged and only round it when printing?
How many decimal places do you want to round to?
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
Are you referring to the values in the variables or the Strings that are printed?
The values in the variables will always have the same significance unless you change them.
To round a double to the second decimal place, add .005, multiply by 100, convert to int and divide by 100 back into the double.
For example:
double dbl = 96.567899999;
int rnded = (int)((dbl + .005) * 100); // round to 2 decimal places
double dblRnded = rnded/100.0;
System.out.println("dbl=" + dbl + ", dblRnded=" + dblRnded); // dbl=96.567899999, dblRnded=96.57
for example 88.69999999999999 should be 88.69 or 88.70
The first: 88.69 is truncated, the second is rounded
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
how to round ALL the numbers
how would i make the entire matrix rounded and not just one number.
Write code that takes each number in the array and formats it the way you want.
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
@alliswim2010
please read this thread
mKorbel
Veteran Poster
1,141 posts since Feb 2011
Reputation Points: 480
Solved Threads: 224
Another solution would be to use the DecimalFormat class.
public static void main(String[] args) throws Exception {
double[] doubles = {5.300000000000001, 123231.600000000000001, 88.695555555 };
final DecimalFormat fmt = new DecimalFormat(".00");
for (double d : doubles) {
System.out.println(fmt.format(d));
}
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Use the DecimalFormat class.
public static void main(String[] args) throws Exception {
double[] doubles = {5.300000000000001, 123231.600000000000001, 88.695555555 };
final DecimalFormat fmt = new DecimalFormat(".00");
for (double d : doubles) {
System.out.println(fmt.format(d));
}
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734