Format double at least one significant digit in Java / Android

I have a DecimalFormat object that I use to format all of my double values ​​to a given number of digits (let them say 2) when I display them. I would like it to be usually up to 2 decimal places, but I always need at least one significant digit. For example, if my value is 0.2, then my formatter spills out 0.20 and this is wonderful. However, if my value is 0.000034, my formatter will spit out 0.00, and I would prefer my formatter to spit out 0.00003.

The number of formatters in Objective-C makes it very simple, I can just set the maximum number of digits that I want to show to 2, and the minimum number of significant digits to 1, and it gives my desired result, but how can I do it in Java?

I appreciate any help anyone can offer me.

Kyle

Edit: I'm interested in rounding values, so 0.000037 is displayed as 0.00004.

+5
source share
2 answers

This is inefficient, so if you often perform this operation, I would try a different solution, but if you only call it sometimes, this method will work.

import java.text.DecimalFormat;
public class Rounder {
    public static void main(String[] args) {
        double value = 0.0000037d;
        // size to the maximum number of digits you'd like to show
        // used to avoid representing the number using scientific notation
        // when converting to string
        DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################");
        StringBuilder pattern = new StringBuilder().append("0.00");
        if(value < 0.01d){
            String s = maxDigitsFormatter.format(value);
            int i = s.indexOf(".") + 3;
            while(i < s.length()-1){
                pattern.append("0");
                i++;
            }
        }
        DecimalFormat df = new DecimalFormat(pattern.toString());
        System.out.println("value           = " + value);
        System.out.println("formatted value = " + maxDigitsFormatter.format(value));
        System.out.println("pattern         = " + pattern);
        System.out.println("rounded         = " + df.format(value));
    }
}
+2
source
import java.math.BigDecimal;
import java.math.MathContext;


public class Test {

    public static void main(String[] args) {
        String input = 0.000034+"";
        //String input = 0.20+"";
        int max = 2;
        int min =1;
        System.out.println(getRes(input,max,min));
    }

    private static String getRes(String input,int max,int min) {
        double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min));
        int n = (new BigDecimal(input)).scale();
        String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString();
        if(n<max){
            for(int i=0;i<max;i++){
                res+="0";
            }
        }
        return res;
    }
}
0
source

All Articles