简体   繁体   中英

logical decimal formatting in java

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)

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);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM