Java examples for java.text:DecimalFormat
format Double value as
import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; public class Main{ public static void main(String[] argv) throws Exception{ Object o = "java2s.com"; System.out.println(formatDouble(o)); }//from w w w . j a va 2 s . c om public static double formatDouble(Object o) { if (o == null || o.equals("")) { return 0; } String amount = format(o.toString().replace(",", "")); return parseToDouble(amount).doubleValue(); } public static String format(Object o) { if (o == null) { return null; } if ("".equals(o)) { return ""; } int d = Integer.valueOf(2); String temp = String.valueOf((int) Math.pow(10, d)) .replace("1", ""); DecimalFormat format = null; if (temp.length() == 0) { format = new DecimalFormat("#,##0.#"); } else { format = new DecimalFormat("#,##0." + temp); } format.setRoundingMode(RoundingMode.HALF_UP); return format.format(new BigDecimal(String.valueOf(o))); } public static Double parseToDouble(String amout) { if (amout == null) return null; String s = amout.replaceAll(",", ""); return Double.valueOf(s); } }