Format double to Decimal by scale - Android java.lang

Android examples for java.lang:Double

Description

Format double to Decimal by scale

Demo Code

import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static String toDecimal(double d, int scale) {

        String format = ",###0.";
        if (scale > 0) {
            for (int i = 0; i < scale; i++) {
                format = format + "0";
            }/*from w  w w . j  a  v  a 2  s .  c om*/
        } else {
            return (Integer.parseInt(d + "") + "");
        }
        DecimalFormat f = new DecimalFormat(format);
        String s = f.format(d);
        return s;
    }
    public static String toDecimal(double d) {
        if (d == 0) {
            return "0.00";
        }
        DecimalFormat f = new DecimalFormat(",###0.00");
        String s = f.format(d);

        return s;
    }

}

Related Tutorials