格式化toString中的货币输出

时间:2015-03-11 03:40:28

标签: java formatting tostring

我的代码工作正常,但格式错误。例如,它输出: Teriyaki $ 0.25当我需要它输出Teriyaki $ .25。唯一输出错误的是小数前面的0。其余的都是正确的。我怎样才能解决这个问题?这是我的代码:

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()));
}
}

测试代码是:

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();
}

}

谢谢

1 个答案:

答案 0 :(得分:3)

创建一个DecimalFormat来构建十进制数字的显示方式

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

格式中的#表示:

  

数字,零表示缺席

将输出.25但如果非零则仍显示前导数