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.
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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With