morc said:
hey,
I've been googling ways to round up decimals to the nearest tenth. e.g
0.266 would round up to 0.3
anybody know which class/methods i should use for this.
I can' seem to be able to locate it in Java Docs.
All suggestinos are appreciated
thanks again
A few years ago, I had a project where I had to round a lot of decimal
numbers to a certain number of decimal places and I asked a similar
question. I was told that you should multiply, then round, then divide to
get the desired precision.
For example, to round to the nearest tenth, multiply your number by 10, use
the integer round() method, then divide by 10 again. To round to the nearest
hundredth, multiply by 100, use the integer round() method, then divide by
100 again.
These two fragmenst illustrates the technique and includes printlns to show
each intermediate result.
double myDouble = 2.456;
System.out.println("myDouble = " + myDouble);
double myDoubleMultiplied = myDouble * 10;
System.out.println("myDoubleMultipled = " + myDoubleMultiplied);
double myDoubleRounded = Math.round(myDoubleMultiplied);
System.out.println("myDoubleRounded = " + myDoubleRounded);
double myDoubleDivided = myDoubleRounded / 10.0;
System.out.println("myDoubleDivided = " + myDoubleDivided);
double myDouble = 2.456;
System.out.println("myDouble = " + myDouble);
double myDoubleMultiplied = myDouble * 100;
System.out.println("myDoubleMultipled = " + myDoubleMultiplied);
double myDoubleRounded = Math.round(myDoubleMultiplied);
System.out.println("myDoubleRounded = " + myDoubleRounded);
double myDoubleDivided = myDoubleRounded / 100.0;
System.out.println("myDoubleDivided = " + myDoubleDivided);