170

Possible Duplicate:
Round a double to 2 significant figures after decimal point

I know that there are plenty of examples on how to round this kind numbers. But could someone show me how to round double, to get value that I can display as a String and ALWAYS have 2 decimal places?

Community
  • 1
  • 1
goodm
  • 7,275
  • 6
  • 31
  • 55
  • 3
    http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html this will be your friend. – STT LCU Feb 20 '12 at 18:18
  • 2
    double myNum = 34.393893 DecimalFormat df = new DecimalFormat("#.##"); String twoDigitNum = df.format(myNum); – koopaking3 Feb 20 '12 at 18:23

2 Answers2

532

You can use String.format("%.2f", d), your double will be rounded automatically.

OleGG
  • 8,589
  • 1
  • 28
  • 34
  • 9
    yes, this I was looking for, but should be: String.format("%.2f", d), thanks – goodm Feb 20 '12 at 18:27
  • 19
    A safer way would be to use a DecimalFormat. With your method there is an option that the formatting will go wrong in some countries, which you would never notice as a developer and probably aren't willing to check for. A better way is to do it like this: DecimalFormat percentageFormat = new DecimalFormat("00.00"); String finalPercentage = percentageFormat.format(percentage); – Yenthe Nov 10 '13 at 16:41
  • 24
    Be careful of the Locale. In French (Canada), it'll use a comma instead of decimal. Force Locale like this (Example): `String.format(Locale.CANADA, "%.2f", d)` – level32 Jan 26 '16 at 18:08
  • But this will convert it to String! :/. – M. Usman Khan Apr 01 '16 at 07:12
  • 1
    @usman original question was about converting to String with fixed precision, so there is nothing wrong with it – OleGG Apr 05 '16 at 01:43
  • Using string format with this method is not safe. If your app will be used internationally you will start receiving a lot of crash reports. reporting either NumberFormatExceptions or RuntimeExceptions. The reason is some countries use a comma as there decimal seperator and others use a period. useing decimal format or number format is a much safer approach. Of course forcing locale can be done also, but it may confuse users that are not used to seeing a period as their decimal seperator. – Thunderstick Nov 01 '17 at 14:05
  • 9
    If you are messed up in certain locales. then this will be the best solution: `Double rounded= new BigDecimal(myDouble).setScale(2, RoundingMode.HALF_UP).doubleValue();` – Bilal Ahmed May 23 '18 at 06:25
13

One easy way to do it:

    Double d;
    Int i;
    D+=0.005;
    i=d*100;
    Double b = i/100;
    String s = b.toString():
halfer
  • 19,824
  • 17
  • 99
  • 186
jersam515
  • 657
  • 6
  • 22