Bharani
Bharani

Reputation: 439

display leading zero using Decimal format

I am trying to display the leading zero of a decimal using Decimal Format... My code is as follows:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;

public class ElementValueUtil {
    public static String formatDoubleNonExponential(double value) {
        return formatDoubleNonExponential(value, null);
    }

    public static String formatDoubleNonExponential(double value, String elementName) {
        DecimalFormat decimalFormat = new DecimalFormat();

        Integer decimalPrecision = 5;
        decimalFormat.setMaximumFractionDigits(decimalPrecision);
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        String exponentialNum = decimalFormat.format(value);
        try{
            return String.valueOf(decimalFormat.parse(exponentialNum));
        }catch(ParseException exception){
            return String.valueOf(value);
        }
    }

    public static void main(String[] args) {
        Double num = 12.4567012;
        System.out.println(formatDoubleNonExponential(num));
    }
}

I am getting output as "12.4567" But I am expecting "12.45670"

Any help will be appreciated...

NOTE: The integer portion may have any number of digits or may not have any digit... but the fraction part should round to 5 decimals if it has more than 5 decimals

For example 
Input        Output
12.25        12.25
125.2345     125.2345
12.12340675  12.12341
12.12340123  12.12340

Upvotes: 2

Views: 618

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

static String format(double d) {
    String s  = new DecimalFormat("").format(d);
    if (s.length() - s.indexOf(',') > 5) {
        s = String.format("%.5f", d);
    }
    return s;
}

public static void main(String[] args) throws Exception {
    System.out.println(format(12.25));
    System.out.println(format(125.2345));
    System.out.println(format(12.12340675));
    System.out.println(format(12.12340123));
}

output

12.25
125.2345
12.12341
12.12340

Upvotes: 1

Related Questions