Here you can find the source of doubleToString(double inValue, int precision, boolean useComma)
public static String doubleToString(double inValue, int precision, boolean useComma)
//package com.java2s; /*/*w w w. j a v a2 s . c o m*/ * Copyright 2010 the original author or authors. * Copyright 2010 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { public static String doubleToString(double inValue, int precision) { return doubleToString(inValue, precision, false); } public static String doubleToString(double inValue, int precision, boolean useComma) { boolean trailingZero; double absval = Math.abs(inValue); // get positive portion if (precision < 0) { precision = -precision; trailingZero = false; } else trailingZero = true; String signStr = ""; if (inValue < 0) signStr = "-"; long intDigit = (long) Math.floor(absval); // get integer part String intDigitStr = String.valueOf(intDigit); if (useComma) { int intDigitStrLen = intDigitStr.length(); int digIndex = (intDigitStrLen - 1) % 3; digIndex++; String intCommaDigitStr = intDigitStr.substring(0, digIndex); while (digIndex < intDigitStrLen) { intCommaDigitStr += "," + intDigitStr.substring(digIndex, digIndex + 3); digIndex += 3; } intDigitStr = intCommaDigitStr; } String precDigitStr = ""; long precDigit = Math.round((absval - intDigit) * Math.pow(10.0, precision)); precDigitStr = String.valueOf(precDigit); // pad zeros between decimal and precision digits String zeroFilling = ""; for (int i = 0; i < precision - precDigitStr.length(); i++) zeroFilling += "0"; precDigitStr = zeroFilling + precDigitStr; if (!trailingZero) { int lastZero; for (lastZero = precDigitStr.length() - 1; lastZero >= 0; lastZero--) if (precDigitStr.charAt(lastZero) != '0') break; precDigitStr = precDigitStr.substring(0, lastZero + 1); } if (precDigitStr.equals("")) return signStr + intDigitStr; else return signStr + intDigitStr + "." + precDigitStr; } }