-1

I created this code to display a certain output however the output is displayed with as so:

First Class Parcel - Cost is £3.3
John Smith, 1 Downing Street, SQ13 9DD
Weight = 1.342kg.

This piece of code is the part of the output about(First Class Parcel - Cost is £3.3) However instead of displaying 3.3 I want to display 3.30.

@Override
    public String toString() {
        String str = "";
        double cost = 0.00;
            if (this.isFirstClass()){
                cost = 3.30;
                str = "First Class Parcel";
            } else {
                cost = 2.80;
                str = "Second Class Parcel"; 
            }
                return str + " - Cost is £" + cost + "\n" + super.toString() + "\n";
        }
azurefrog
  • 10,785
  • 7
  • 42
  • 56
Sheeparito
  • 43
  • 3
  • 9
  • So, format the value the way you want it. – Hot Licks Nov 16 '15 at 00:04
  • Look into [`DecimalFormat`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html) – Vince Nov 16 '15 at 00:05
  • https://docs.oracle.com/javase/tutorial/java/data/numberformat.html – ajb Nov 16 '15 at 00:05
  • 1
    By the way, you generally shouldn't use `double` for monetary amounts, because the values 3.30 and 2.80 cannot be represented exactly by a `double`. You can look at http://www.adambeneschan.com/How-Does-Floating-Point-Work/ to see what the actual value will be, and why. For small amounts like this, it's unlikely to make a difference. But for future use, you'll want to look into the `BigDecimal` class. – ajb Nov 16 '15 at 00:08

3 Answers3

0

Have you tried:

String.format( "%.2f", cost);

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)

JamesB
  • 7,774
  • 2
  • 22
  • 21
0

This will help you :

DecimalFormat df = new DecimalFormat("#.00");
        double d= 23.2;
        System.out.println(df.format(d));
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
0

Use DecimalFormat. Something on the lines like following

    double cost = 3.30;
    DecimalFormat df = new DecimalFormat("#.00"); 

    System.out.println("Cost is £" + df.format(cost) );
Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34