Home DecimalFormat newFormat = new DecimalFormat("##.##");
Reply: 1

DecimalFormat newFormat = new DecimalFormat("##.##");

Doomon
1#
Doomon Published in 2018-02-14 05:21:59Z

DecimalFormat newFormat = new DecimalFormat("##.##"); giving me unexpected result for the below values:

for value 0.005 = 0.00
          0.015 = 0.02

DecimalFormat is not formatting the 0.005 to 0.01. Please let me know how to get the value of 0.005 to 0.01 when DecimalFormat newFormat = new DecimalFormat("##.##"); is provided.

Thanks in Advance.

Unknown
2#
Unknown Reply to 2018-02-14 07:01:24Z

After watching your comment, you can manually round to 2 digit and then do Decimal Format.

Here is the example:

public static void main(String[] args) {
    double input = 0.004;
    DecimalFormat formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.005;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.015;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
}

private static DecimalFormat getDecimalFormat(double input){
    DecimalFormat formatter = (input % 1 == 0) ? new DecimalFormat("##.##"): new DecimalFormat("#0.00"); 
    return formatter;
}

private static double round2Digit(double input){
    double result = input * 100;
    result = Math.round(result);
    result = result / 100;
    return result;
}

Output:

0.00

0.01

0.02

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342126 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO