-1

I have a small problem which i can't seem to solve.

I want to print out my Balance in a '£100.50' format but it's currently giving me a '£100.5' format.

I'm using a decimalFormat method but it's not working. Any help why?

final DecimalFormat df2 = new DecimalFormat("#.##");

balance = 100.499999;
System.out.println("Balance: £ " + df2.format(balance));

Fixed the error by changing ("#.##") to ("#.00")

AnotherUser
  • 139
  • 1
  • 2
  • 15
  • 1
    See this one http://stackoverflow.com/questions/8819842/best-way-to-format-a-double-value-to-2-decimal-places – nerdlyist Feb 19 '16 at 18:16
  • @TomasBisciak Nope doesn't work gives me an error – AnotherUser Feb 19 '16 at 18:16
  • @imraanstack1 Did any of these worked for you ? Please accept answer if it works for you, also there are some quesitons you had and didnt marked as answered , check them out in your profile to give people reward for theyr help. – Tomas Bisciak Feb 19 '16 at 18:21

3 Answers3

2

This works: new DecimalFormat("0.00");

UPDATE

For a complete understanding of the patterns used in java.text.DecimalFormat refer to Java API https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

ahoxha
  • 1,919
  • 11
  • 21
1
final DecimalFormat df2 = new DecimalFormat("#.00");
balance = 100.499999;
System.out.println("Balance: £ " + df2.format(balance));

This should work

From @A2H's answer I would like to make a note.

Suppose, you have

balance = .7538;

If you want it to be 0.75 then use

new DecimalFormat("0.00");

or if you want to be .75 then use

new DecimalFormat("#.00");
Nikitha
  • 373
  • 2
  • 18
0
double value= 213.3456;
DecimalFormat df = new DecimalFormat("#.00");      
System.out.println(df.format(value));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97