-3

amount / 100 * 7 - I'am trying to get a percent from an amount, but the problem is that sometimes a get a number with to many digits after dot, how can I make it strictly return 2 digits after dot?

type is double

user3518675
  • 95
  • 3
  • 7
  • 1
    it doesn't "return two digits". it returns a `double`, however many decimal digits worth of precision that would signify (14...16, IIRC). You may want to **format** your output, though. – The Paramagnetic Croissant Apr 30 '14 at 10:39

2 Answers2

1

Use DecimalFormat API

        double d = amount / 100 * 7;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(d));

"##" denotes the 2 digit precision

Keerthivasan
  • 12,040
  • 2
  • 26
  • 49
0

You can do this

 double d = Math.round(amount * 7) / 100.0;

This will give you have value which has two decimal places. (for a modest range of values i.e. < 70e12)

If you just want to print two decimal places you can use

System.out.printf("%.2f%n", d);
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075