Rounds a double value to a certain number of digits - Android java.lang

Android examples for java.lang:Math

Description

Rounds a double value to a certain number of digits

Demo Code


//package com.java2s;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class Main {
    /**/*from  w ww .  j  av  a  2 s .c  o  m*/
     * Rounds a double value to a certain number of digits
     * @param toBeRounded -number to be rounded
     * @param digits -number of digits to be rounded
     * @param locale -{@link Locale}
     * @return double -rounded double 
     */
    public static double round(double toBeRounded, int digits, Locale locale) {
        if (digits < 0) {
            return 0;
        }
        String formater = "";
        for (int i = 0; i < digits; i++) {
            formater += "#";
        }

        DecimalFormat twoDForm = new DecimalFormat("#." + formater,
                new DecimalFormatSymbols(locale));
        return Double.valueOf(twoDForm.format(toBeRounded));
    }
}

Related Tutorials