ConvertUtil { @NonNull static String formatDouble(double value, int precision) { if (value < 0) return "-" + formatDouble(-value, precision); if (Double.isNaN(value) || Double.isInfinite(value)) return Double.toString(value); if (value == 0.0) return "0"; if (precision <= 0) precision = 1; final int mag = (int) Math.floor(Math.log10(value)); final int digits = (int) Math.floor(value * Math.pow(10, precision - mag - 1)); final int decimalPlaces = precision - mag - 1; if (decimalPlaces <= 0) { final char[] zeros = new char[-decimalPlaces]; Arrays.fill(zeros, '0'); return digits + new String(zeros); } else if (precision < decimalPlaces) { final char[] zeros = new char[decimalPlaces - precision]; Arrays.fill(zeros, '0'); return "." + new String(zeros) + digits; } else { final String digitsString = Integer.toString(digits); final String before = digitsString.substring(0, precision - decimalPlaces); final String after = digitsString.substring(precision - decimalPlaces); return before + "." + after; } }    }
@Test public void convertFormatDouble() { assertEquals( "0", ConvertUtil.formatDouble(0.0, 2)); assertEquals( "1.0", ConvertUtil.formatDouble(1.0, 2)); assertEquals( "9", ConvertUtil.formatDouble(9.8, 0)); assertEquals( "9", ConvertUtil.formatDouble(9.8, 1)); assertEquals( "9.8", ConvertUtil.formatDouble(9.8, 2)); assertEquals( "9.80", ConvertUtil.formatDouble(9.8, 3)); assertEquals( "10", ConvertUtil.formatDouble(10, 1)); assertEquals( "10", ConvertUtil.formatDouble(10, 2)); assertEquals( "10.0", ConvertUtil.formatDouble(10, 3)); assertEquals( "3200", ConvertUtil.formatDouble(3280, 2)); assertEquals( "3280", ConvertUtil.formatDouble(3280, 3)); assertEquals( "3280", ConvertUtil.formatDouble(3280, 4)); assertEquals( "3280.0", ConvertUtil.formatDouble(3280, 5)); assertEquals( "3280.00", ConvertUtil.formatDouble(3280, 6)); assertEquals( "-9", ConvertUtil.formatDouble(-9.8, 1)); assertEquals( "-9.8", ConvertUtil.formatDouble(-9.8, 2)); assertEquals( "-9.80", ConvertUtil.formatDouble(-9.8, 3)); assertEquals( "9.2", ConvertUtil.formatDouble(9.2, 2)); assertEquals( ".92", ConvertUtil.formatDouble(0.92, 2)); assertEquals( ".092", ConvertUtil.formatDouble(0.092, 2)); assertEquals( ".0092", ConvertUtil.formatDouble(0.0092, 2)); assertEquals( ".098", ConvertUtil.formatDouble(0.098, 2)); assertEquals( ".99", ConvertUtil.formatDouble(0.999, 2)); assertEquals( "NaN", ConvertUtil.formatDouble(Double.NaN, 2)); assertEquals( "Infinity", ConvertUtil.formatDouble(Double.POSITIVE_INFINITY, 2)); assertEquals( "-Infinity", ConvertUtil.formatDouble(Double.NEGATIVE_INFINITY, 2)); }