get Format for Distance in unit - Android java.lang

Android examples for java.lang:Integer

Description

get Format for Distance in unit

Demo Code

import android.text.TextUtils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Main{

    public static String getFormatDistance(int mile, int decimalNum,
            String unitM, String unitKm) {
        String format = "";
        if (mile <= 1000) {
            format = mile + unitM;//from www.  j  a  v a2s .c o m
        } else {
            float f = mile / 1000f;
            format = getFormatDecimal(f, decimalNum) + unitKm;
        }
        return format;
    }
    public static String getFormatDecimal(double data, int decimalNum) {
        String format = "";
        try {
            StringBuilder fs = new StringBuilder();
            fs.append("#.");
            if (decimalNum < 1) {
                decimalNum = 3;
            }
            for (int i = 0; i < decimalNum; i++) {
                fs.append("#");
            }
            DecimalFormat df = new DecimalFormat(fs.toString());
            format = df.format(data);
        } catch (Exception e) {
            // TODO: handle exception
            e.toString();
        }
        return format;
    }
}

Related Tutorials