1

I was going through the class decimal format as I was trying format a decimal number in Java upto 2 decimal places or 3 decimal places.

I come up with this solution as shown below but please also let me know are there any other alternative that java provides us to achieve the same thing..!!

import java.text.DecimalFormat;

public class DecimalFormatExample {   

    public static void main(String args[])  {

        //formatting numbers upto 2 decimal places in Java
        DecimalFormat df = new DecimalFormat("#,###,##0.00");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));

        //formatting numbers upto 3 decimal places in Java
        df = new DecimalFormat("#,###,##0.000");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));
    }

}

Output:
364,565.14
364,565.15
364,565.140
364,565.145

Please advise what are other alternatives that java provide us to achieve the same thing..!!

Jonik
  • 80,077
  • 70
  • 264
  • 372
user1614879
  • 43
  • 1
  • 5
  • 3
    Is there anything about this solution that you're not happy with? – hcarver Aug 22 '12 at 17:33
  • I am not sure I understand what your problem with the above code is... – posdef Aug 22 '12 at 17:33
  • 1
    E.g. this question contains a couple of ways to do rounding / truncating / formatting of doubles: http://stackoverflow.com/q/2808535/56285 But if DecimalFormat does what you need, why not just use that? – Jonik Aug 22 '12 at 17:38

3 Answers3

1

If you are bothered by re-defining your DecimalFormat, or if you suspect you'll be needing to do redefine many times, you could also do inline formatting with String.format(). Check the syntax for Formatter especially the Numeric sub-title.

posdef
  • 6,498
  • 11
  • 46
  • 94
0

Here is an alternative to round off...

double a = 123.564;
double roundOff = Math.round(a * 10.0) / 10.0;
System.out.println(roundOff);
roundOff = Math.round(a * 100.0) / 100.0;
System.out.println(roundOff);

The output is

123.6
123.56

Number of 0s while multiplying and dividing decides the rounding off.

Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
0

Here is one method.

float round(float value, int roundUpTo){
     float x=(float) Math.pow(10,roundUpTo);
     value = value*x; // here you will guard your decimal points from loosing
     value = Math.round(value) ; //this returns nearest int value
     return (float) value/p;
}
Aman J
  • 1,825
  • 1
  • 16
  • 30