Here you can find the source of formatDouble(double inDouble, boolean inComma, int inCommaPos)
public static final String formatDouble(double inDouble, boolean inComma, int inCommaPos)
//package com.java2s; public class Main { /**/*from w w w . ja va 2s .c o m*/ * This function is to format the double value. **/ public static final String formatDouble(double inDouble) { return formatDouble(inDouble, false, 0); } /** * This function is to format the double value. **/ public static final String formatDouble(double inDouble, boolean inComma, int inCommaPos) { int dp = 0; long tens = 1; long tempInt = (long) (fixDouble(inDouble * tens)); while (fixDouble(inDouble * tens) != tempInt) { dp++; tens = tens * 10; tempInt = (long) (fixDouble(inDouble * tens)); } return formatDouble(inDouble, dp, inComma, inCommaPos); } /** * This function is to format the double value. **/ public static final String formatDouble(double inDouble, int inDP, boolean inComma, int inCommaPos) { return formatDouble(inDouble, inDP, inComma, inCommaPos, true); } /** * This function is to format the double value. **/ public static final String formatDouble(double inDouble, int inDP, boolean inComma, int inCommaPos, boolean isRound) { String outString = ""; long tempLong; int countComma = 0; boolean fNegative = false; if (inDouble < 0) { fNegative = true; inDouble = inDouble * (-1); } if (isRound && inDP >= 0) { /* * Nelson Chan - 2011/03/02 - Fix rounding method Use Math.round on * the double raised with a factor of 10^(Decimal Place), then * normalize the rounded number by the same factor */ // inDouble = inDouble + (0.5 * Math.pow(0.1, inDP)); double factor = Math.pow(10, inDP); inDouble = ((double) Math.round(inDouble * factor)) / factor; } long intPart = (long) (inDouble); if (intPart == 0) outString = "0"; else { while (intPart > 0) { if (inComma && countComma == inCommaPos) { outString = "," + outString; countComma = 0; } tempLong = intPart % 10; outString = Long.toString(tempLong) + outString; intPart = (long) (intPart / 10); countComma++; } } if (inDP > 0) { outString = outString + "."; int tempDP = 0; inDouble = fixDouble(inDouble - Math.floor(inDouble)); while (tempDP < inDP) { tempDP++; inDouble = fixDouble(inDouble * 10); tempLong = (long) (Math.floor(inDouble)); outString = outString + Long.toString(tempLong); inDouble = fixDouble(inDouble - Math.floor(inDouble)); } } if (fNegative) outString = "-" + outString; return outString; } public static final double fixDouble(double inValue) { int dp; if (inValue > 1E8 || inValue < -1E8) dp = 5; else dp = 7; return fixDouble(inValue, dp); } public static final double fixDouble(double inValue, int dp) { double base = Math.pow(10, dp); long outValue = ((long) (inValue * base + ((inValue < 0) ? -0.1 : 0.1))); return outValue / base; } }