# How to make Math.round() round to the nearest .1?

• February 2nd, 2013, 05:27 PM
bdennin
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)
• February 2nd, 2013, 05:46 PM
Norm
Re: How to make Math.round() round to the nearest .1?
One idea: *10, round, /10
• February 2nd, 2013, 05:48 PM
pbrockway2
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.
• February 2nd, 2013, 05:59 PM
bdennin
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.
• February 2nd, 2013, 06:23 PM
pbrockway2
Re: How to make Math.round() round to the nearest .1?
You're welcome.