Here you can find the source of formatFloat(double number, int precision)
public static String formatFloat(double number, int precision)
//package com.java2s; //License from project: Open Source License public class Main { public static final int PRECISION = 1; /**//from w w w . j a v a 2 s.c om * Returns the specified double, formatted as a string, to n decimal places, * as specified by precision. * <p/> * ie: formatFloat(1.1666, 1) -> 1.2 ie: formatFloat(3.1666, 2) -> 3.17 ie: * formatFloat(3.1666, 3) -> 3.167 */ public static String formatFloat(double number, int precision) { String text = Double.toString(number); if (precision >= text.length()) { return text; } int start = text.indexOf(".") + 1; if (start == 0) return text; if (precision == 0) return text.substring(0, start - 1); if (start <= 0) return text; else if ((start + precision) <= text.length()) return text.substring(0, (start + precision)); else return text; } public static String formatFloat(String text, int precision) { int start = text.indexOf(".") + 1; if (start == 0) return text; if (precision == 0) return text.substring(0, start - 1); if (start <= 0) { return text; } else if ((start + precision) <= text.length()) { return text.substring(0, (start + precision)); } else return text; } /** * Returns the specified double, formatted as a string, to n decimal places, * as specified by precision. * <p/> * ie: formatFloat(1.1666, 1) -> 1.2 ie: formatFloat(3.1666, 2) -> 3.17 ie: * formatFloat(3.1666, 3) -> 3.167 */ public static String formatFloat(double number) { String text = Double.toString(number); if (PRECISION >= text.length()) { return text; } int start = text.indexOf(".") + 1; if (start == 0) return text; if (start <= 0) { return text; } else if ((start + PRECISION) <= text.length()) { return text.substring(0, (start + PRECISION)); } else return text; } }