Java Double Number Format format(double value, int decimalPlaces)

Here you can find the source of format(double value, int decimalPlaces)

Description

format

License

Apache License

Return

value formatted as commas to decimalPlaces , e.g. 1000.125 as "1,000.13".

Declaration

public static String format(double value, int decimalPlaces) 

Method Source Code

//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);
    }
}

Related

  1. format(Double number)
  2. format(double number, int nums)
  3. format(double number, int precision)
  4. format(double size, String type)
  5. format(double val, int n, int w)
  6. format(double value, int digits)
  7. format(final double power)
  8. formatDouble(double d)
  9. formatDouble(double d)