DecimalUtil { public static String toString(double value, int precision) { StringBuilder buf = new StringBuilder("0"); if (precision > 0) { buf.append("."); } for (int i = 0; i < precision; i++) { buf.append("0"); } DecimalFormat format = new DecimalFormat(buf.toString()); return format.format(value); }  static String toString(double value, int precision);  }
@Test public void toStringWithPrecision() { String result = null; result = DecimalUtil.toString(0, 0); Assert.assertEquals("0", result); result = DecimalUtil.toString(1.12, 0); Assert.assertEquals("1", result); result = DecimalUtil.toString(1.1, 0); Assert.assertEquals("1", result); result = DecimalUtil.toString(1.12, 1); Assert.assertEquals("1.1", result); result = DecimalUtil.toString(1.12, 2); Assert.assertEquals("1.12", result); result = DecimalUtil.toString(1.12, 3); Assert.assertEquals("1.120", result); result = DecimalUtil.toString(1, 4); Assert.assertEquals("1.0000", result); double d0 = (double)1/(double)818393434343431121L; result = DecimalUtil.toString(d0, 2); Assert.assertEquals("0.00", result); }