Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format double values using a maximum of five total digits, rounding decimal digits if necessary

I have double values which I would like to convert to String values with the following format restrictions:

number_of_fraction_digits = max( 0, 5 - number_of_integer_digits )

Essentially I want to keep the number of digits to 5 if possible, rounding decimal digits if necessary. For example:

 float          String
-------------------------
     1               1
   100             100
100000          100000
 99999           99999
 99999.99        99999
  9999.99         9999.9
   999.99          999.99
    23.34324        23.343

I've looked into using DecimalFormat but as far as I can tell it doesn't quite accomplish what I'm after.

It allows setting of the maximum number of decimal digits using setMaximumFractionDigits() but as far as I can tell I would have to calculate the number of integer digits and perform the above calculation myself.

So the basic question is whether there is a nice, clean built-in way to format numbers in this way.

like image 617
ulmangt Avatar asked Apr 02 '12 14:04

ulmangt


1 Answers

public class SignificantFormat {

    public static String formatSignificant(double value, int significant)
    {
        MathContext mathContext = new MathContext(significant, RoundingMode.DOWN);
        BigDecimal bigDecimal = new BigDecimal(value, mathContext);
        return bigDecimal.toPlainString();
    }

    public static void main(String[] args) {
        double[] data = { 1, 100, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324 };
        for(double d: data){
            System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), formatSignificant(d, 5));
        }
    }
}
like image 103
ecle Avatar answered Sep 20 '22 21:09

ecle