1

When it comes to formatting decimals in java there is one approach i know of

NumberFormat formatter = new DecimalFormat("#0.00");  

but this is not working if you may have values such as

0.0000054654654 or similar

in that case you'll just get

0.00

while more logically it would make sence to print

0.0000054 (or maybe 0.0000055)

I wonder if there is already a solution for this? or i have to implement custom formatter?

examples that might be there

1.1 -> 1.100 0.00000011111 -> 0.000000111

you can see that instead of hardcoding how many digits after decimal point we want, we need to tell how many digits we want after first digit... (roughly)

vach
  • 10,571
  • 12
  • 68
  • 106

1 Answers1

0
NumberFormat formatter = new DecimalFormat("#0.00");  

The number of 0s specifies the precision. If you want 0.0000054654654 to be formatted to 0.0000055, use: NumberFormat formatter = new DecimalFormat("#0.000000");

If required precision in not known upfront, the following approach may be used:

public static void main(String[] args) {
    double a = 0.0000054654654;
    BigDecimal bd = new BigDecimal(a);
    String answer = String.format("%."+3+"G", bd);
    System.out.println(answer);
} 
Anurag Kapur
  • 675
  • 4
  • 19
  • the problem is that you dont know if you'll get 1.1 or 0.000000023423, in your case if i use #0.000000 and have 0.00000000000000123 then i'll get another 0.0000000 output – vach Feb 20 '15 at 15:47
  • 1
    I think the op wants 2 significant digitis - so for example: 1 -> 1.0, 1.123 -> 1.12, 0.000023 -> 0.00023 – assylias Feb 20 '15 at 15:48
  • exactly, i've updated question also to make that clear... i think this might be a common issue thats why i expect some solution already done for it (before i invent another bike) – vach Feb 20 '15 at 15:50
  • 1
    ahh, understood. Does this help: http://stackoverflow.com/questions/19487506/built-in-methods-for-displaying-significant-figures/19506712#19506712 – Anurag Kapur Feb 20 '15 at 15:51
  • I've tried it, thanks for reference, its interesting yet not exactly what is needed... – vach Feb 20 '15 at 15:57