0

How can i return back the double value with 2 decimals place in Java program?

public String toString() 
    { 
      return  "\nCost: $" +computeRentalCost() ;
    }
user5000
  • 37
  • 1
  • 6
  • If you are using a `double` you're SOL; it cannot be reliably "truncated" to two decimals. For this you'd need a `BigDecimal`. – fge Apr 14 '14 at 07:24
  • Recommend you to read this thread regarding accuracy of double/float for currency http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – Sky Apr 14 '14 at 07:28

1 Answers1

2

You can use String.format():

return String.format("\nCost: $%.2f", computeRentalCost());

The format modifier %.2f tells that only two decimal places will be shown.

Note:

  • This won't modify the number, it only modifies the way it's shown.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73