Sammie
Sammie

Reputation: 21

Formatting my currency output in toString

My code is working fine except for that the formatting is wrong. For example it is outputting: Teriyaki $0.25 when I need it to output Teriyaki $.25. The only things outputting wrong are with the 0 in front of the decimal. the rest is correct. How can I fix this? Here is my code:

import java.text.NumberFormat;

public class MenuItem 
{
private String name;
private double price;

public MenuItem (String name, double price)
{
    this.name = name;
    this.price = price;
}

public String getName()
{
    return name;
}

public double getPrice()
{
    return price;
}

public String toString()
{
    return (getName() + " " + NumberFormat.getCurrencyInstance().format(getPrice()));
}
}

The test code is:

import java.util.Scanner;
import java.util.Vector;

public class sol
{
public static void main(String[] args)
{
    /* Read from keyboard */
    Scanner keys = new Scanner(System.in);
    /* Create dynamic list */
    Vector<MenuItem> list = new Vector<MenuItem>();
    /* While there is input waiting */
    while (keys.hasNext())
    {
        /* Prompt the user */
        System.out.println("Enter product name and price");
        /* Test the constructor */
        list.add(new MenuItem(keys.next(), keys.nextDouble()));
    }
    /* Test toString (implicitly called when passed to println) */
    System.out.println("Testing toString");
    for (MenuItem mi : list)        
        System.out.println(mi);
    /* Test getters */
    System.out.println("Testing getters");
    for (MenuItem mi : list)        
        System.out.println("Item: " + mi.getName() + " Price: " +   mi.getPrice()); 
    /* Close keyboard stream */
    keys.close();
}

}

Thank you

Upvotes: 0

Views: 1257

Answers (1)

Sean F
Sean F

Reputation: 2390

Create a DecimalFormat to structure decimal numbers how you want them to appear

    DecimalFormat twoDForm = new DecimalFormat("#.00");
    Double d = Double.parseDouble("0.25");
    String s = twoDForm.format(d);
    System.out.println(s);

The # in the format indicates:

Digit, zero shows as absent

which will output .25 but still show a leading number if it is non zero

Upvotes: 3

Related Questions