Here you can find the source of formatDouble(double value)
Parameter | Description |
---|---|
value | the value to format |
public static String formatDouble(double value)
//package com.java2s; public class Main { /**/*from w w w . jav a2 s .c o m*/ * Formats a value with two decimals, using spaces to separate * thousands as: <em>ddd ddd ddd.dd</em>. * * @param value the value to format * @return the formatted value as a string */ public static String formatDouble(double value) { boolean isNegative = value < 0.0 || (value == 0.0 && 1 / value < 0.0); if (isNegative) { value = -value; } // -9 223 372 036 854 775 808.00 char[] buffer = new char[1 + 19 + 6 + 3]; long intValue = (long) value; int decValue = (int) ((value - intValue) * 100 + 0.5); int index = buffer.length - 1; buffer[index--] = (char) ('0' + (decValue % 10)); buffer[index--] = (char) ('0' + ((decValue / 10) % 10)); buffer[index--] = '.'; if (intValue == 0) { buffer[index--] = '0'; } else { for (int count = 0; intValue > 0 && index >= 0; count++) { if (((count % 3) == 0) && count > 0 && index > 0) { buffer[index--] = ' '; } buffer[index--] = (char) ('0' + (intValue % 10)); intValue /= 10; } } if (isNegative && index >= 0) { buffer[index--] = '-'; } return new String(buffer, index + 1, buffer.length - index - 1); // long i = (long) value; // if (value < 0) { // value = -value; // } // long dec = ((long) (0.5 + value * 100)) % 100; // return "" + i + '.' + (dec < 10 ? "0" : "") + dec; } /** * Formats a value with two decimals, using the specified separator * to separating thousands as: * <em>ddd&nbsp;ddd&nbsp;ddd.dd</em> (with "&nbsp;" as * separator). * * @param value the value to format * @param separator the separator to use * @return the formatted value as a string */ public static String formatDouble(double value, String separator) { boolean isNegative = value < 0.0 || (value == 0.0 && 1 / value < 0.0); if (isNegative) { value = -value; } // -9 223 372 036 854 775 808.00 int sepLen = separator.length(); int maxLen = 1 + 19 + 6 * sepLen + 3; char[] buffer = new char[maxLen]; long intValue = (long) value; int decValue = (int) ((value - intValue) * 100 + 0.5); int index = maxLen - 1; buffer[index--] = (char) ('0' + (decValue % 10)); buffer[index--] = (char) ('0' + ((decValue / 10) % 10)); buffer[index--] = '.'; if (intValue == 0) { buffer[index--] = '0'; } else { for (int count = 0; intValue > 0 && index >= 0; count++) { if (((count % 3) == 0) && count > 0 && index > sepLen) { index -= sepLen; separator.getChars(0, sepLen, buffer, index + 1); } buffer[index--] = (char) ('0' + (intValue % 10)); intValue /= 10; } } if (isNegative && index >= 0) { buffer[index--] = '-'; } return new String(buffer, index + 1, maxLen - index - 1); } }