Here you can find the source of format(double value, int decimalPlaces)
public static String format(double value, int decimalPlaces)
//package com.java2s; //License from project: Apache License public class Main { /** @return {@code value} formatted with commas, e.g. 1000 as "1,000". */ public static String format(final long value) { boolean negative = value < 0; final String num = String.valueOf(Math.abs(value)); String formattedNum = ""; for (int i = num.length() - 1, j = 0; i >= 0; i--, j++) { formattedNum += num.charAt(j); if (i % 3 == 0 && i != 0) { formattedNum += ","; }/* w ww . ja v a 2s . c o m*/ } return negative ? "-" + formattedNum : formattedNum; } /** @return {@code value} formatted as commas to {@code decimalPlaces}, e.g. 1000.125 as "1,000.13". */ public static String format(double value, int decimalPlaces) { if (decimalPlaces == 0) { return format(Math.round(value)); } final long integerPart = (long) value; // Move 123.456 -> 45.6 when decimalPlaces = 2 double adjust = Math.pow(10, decimalPlaces); // We actually do 45.6 + 100 (adjust) so that we get "100" (instead of just "0") and then drop the leading 1 long decimalPart = Math.round((Math.abs(value) * adjust) % adjust) + (long) adjust; return format(integerPart) + "." + Long.toString(decimalPart).substring(1); } }