How to make Math.round() round to the nearest .1?
I want round to round to the nearest 10th instead of the nearest integer... Any ideas?
Code java:
public class Triangle
{
private final int leg;
private final double hypotenuse;
public Triangle( int l )
{
leg = l;
hypotenuse = leg*Math.sqrt( 2.0 );
}
public int getLeg()
{
return leg;
}
public double getHypotenuse()
{
return hypotenuse;
}
@Override
public String toString()
{
return String.format( "Triangle(%d)", leg );
}
}
Triangle(5)
Leg: 5
Hypotenuse: 7.0 (this should be 7.1)
Re: How to make Math.round() round to the nearest .1?
One idea: *10, round, /10
Re: How to make Math.round() round to the nearest .1?
Do do you want to round the value hypotenuse - ie produce a completely different double value - or merely format the value so that it appears with one decimal place?
I ask because people often confuse rounding (double->double) with formatting (double->String). And often imagine that double values have decimal places: in fact decimal places are a property of the String (base 10) representation of double values.
Assuming you want to format you would use
Code :
String.format("%.1f", hypotenuse);
The "f" means you are formatting a floating point value (a double) and the ".1" means you want one decimal place to appear.
Full details in the Formatter API docs. There is rather a lot to absorb there: too much to attempt to remember. But it's worth bookmarking and going back to whenever formatting problems arise.
Re: How to make Math.round() round to the nearest .1?
Code :
String.format("%.1f", hypotenuse);
Ahhh, so easy. I can't believe I didn't think of that. Thank you, as always.
Re: How to make Math.round() round to the nearest .1?