Java BigDecimal Format formatDouble(double d)

Here you can find the source of formatDouble(double d)

Description

format Double

License

Creative Commons License

Declaration

public static String formatDouble(double d) 

Method Source Code

//package com.java2s;
// The license under which this software is released can be accessed at:

import java.math.BigDecimal;

public class Main {
    public static String formatDouble(double d) {
        String[] plain = printDouble(d).split("\\.");
        String formatted = "";
        while (plain[0].length() >= 4) {
            formatted = "'" + plain[0].substring(plain[0].length() - 3) + formatted;
            plain[0] = plain[0].substring(0, plain[0].length() - 3);
        }/*from w w  w  .java 2 s.  c  o m*/
        formatted = plain[0] + formatted;
        if ((plain.length > 1) && (tryParse(plain[1], 0) != 0)) {
            formatted += "." + plain[1];
        }
        return formatted;
    }

    public static String printDouble(double d) {
        return BigDecimal.valueOf(smoothBig(d, 3)).toPlainString();
    }

    public static int tryParse(String s, int i) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return i;
        }
    }

    public static double tryParse(String s, double d) {
        try {
            return Double.parseDouble(s);
        } catch (Exception e) {
            return d;
        }
    }

    public static double smoothBig(double d, int digits) {
        double factor = Math.pow(10, digits);
        return roundBig(d * factor) / factor;
    }

    public static double roundBig(double d) {
        long i = (long) d;
        d -= i;
        return i + (d >= 0.5 ? 1 : (d <= -0.5 ? -1 : 0));
    }
}

Related

  1. formatDecimal(BigDecimal b)
  2. formatDecimal(BigDecimal num)
  3. formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits)
  4. formatDecimalCost(BigDecimal value)
  5. formatDigit(double value, int scale)
  6. formatDouble(Double someDouble, int digitsToTheRightOfDecimal)
  7. formatDouble(Double toFormat)
  8. formatDouble(double value, int decimalPlaces)
  9. formatDoubleNumber(double f)