Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a double with variable amount of decimal digits

I was working on a task where I was struck handling a negative scenario mentioned below

If the Value is less than 1 then I want to format (add) 4 decimal points to it .

For example if value is 0.4567 then I need 0.4567

Or else if the value is greater than 1 format with only 2 digits.

For example if value is 444.9 then I need 444.90

Everything above mentioned is working fine, but struck on this below condition

That is if the value is less than 1 and it ends as zeros (0.1000 , 0.6000) , It makes no sense to print 0.2000, so in that case I want the output to be only as 0.20

This is my program below

package com;
import java.text.DecimalFormat;
public class Test {
    public static void main(String args[]) {
        try {
            String result = "";
            Test test = new Test();
            double value = 444.9;
            if (value < 1) {
                result = test.numberFormat(value, 4);
            } else {
                result = test.numberFormat(value, 2);
            }
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String numberFormat(double d, int decimals) {
        if (2 == decimals)
            return new DecimalFormat("#,###,###,##0.00").format(d);
        else if (0 == decimals)
            return new DecimalFormat("#,###,###,##0").format(d);
        else if (3 == decimals)
            return new DecimalFormat("#,###,###,##0.000").format(d);
        else if (4 == decimals)
            return new DecimalFormat("#,###,###,##0.0000").format(d);
        return String.valueOf(d);
    }

}
like image 797
Pawan Avatar asked Jun 25 '13 11:06

Pawan


1 Answers

use # if you want to ignore 0 in 3rd and 4th decimal places

new DecimalFormat("#,###,###,##0.00##").format(d)
like image 129
chetan Avatar answered Oct 25 '22 00:10

chetan