format any value - Java java.text

Java examples for java.text:DecimalFormat

Description

format any value

Demo Code


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(format(o));
    }//from  w ww  .  ja  v  a  2 s .co  m
    
    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)));
    }
}

Related Tutorials