2013-03-07 59 views
2
public String toString() //toString withing Shiftsupervisor class 
{ 
    String employee = name + ", " + iD + ", " + hireDate + ", $" + AnnualSal + ", $" + ProdBonus; 
    return employee; 
} 

主:格式化方法中的货币?

ShiftSupervisor supervisor1 = new ShiftSupervisor("John Smith", "123-A", "11-15-2005", 48000, 6500); 

System.out.println(supervisor1); 

我已经加入我的toString“$”,但我想这是输出的最后2个双打48,000 6500 < <在逗号加入!

我可以在我的setMethods中做这个吗?

+0

对不起,我不不明白要求是什么 – 2013-03-07 20:12:23

+0

如果我是你,我可能会考虑将你的货币金额存储为整数(代表美分,例如200是$ 2.00)是否可行。如果你对这些数字进行某种算术运算,那么做到这一点可能是不可行的,但这样做会使数字更加具体,并使字符串操作更容易。 – 2013-03-07 20:15:29

+0

如果您发现问题的答案很好,请点击答案主体旁边的向上/向下箭头旁边的检查,将其标记为已接受。 – 2013-03-07 20:45:16

回答

2

不要重新发明轮子。使用已经为你处理的NumberFormat#getCurrencyInstance。这里有一个例子:

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US); 
System.out.println(cnf.format(48000)); // prints $48,000.00 

如果你想省略小数部分,只使用NumberFormat#setMaximumFractionDigits

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US); 
cnf.setMaximumFractionDigits(0); 
System.out.println(cnf.format(48000)); // prints $48,000 

在你的方法实现这个:

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US); 
String employee = name + ", " + iD + 
    ", " + hireDate + 
    ", " + cnf.format(AnnualSal) + 
    ", " + cnf.format(ProdBonus); 
+1

@SotiriosDelimanolis我想现在你的灵魂可以休息了。 – 2013-03-07 20:27:57

+0

就是这样,谢谢! – 2013-03-07 21:25:00

1

我可以在我的setMethods中做这个吗?

是的,你可以,但你不想。相信我这一个。

通常,您将原始值(int,double,float)保存在您的类中,并将它们格式化为get方法。这使您可以根据不同的需要以不同的方式格式化您的课程输出。