我有一个双重类型的值,我从另一个名为Account的类调用,该值保存用户的balance
。每次用户点击按钮时,我都希望将其显示出来。像这样的东西:
该值(取自类帐户)应位于Your current balance(RM):
下方并显示。但是当我在这里使用下面的代码时,它甚至不会运行代码。
Label balanceInfo = new Label("Your current balance (RM) :"+Double.toString(user[currentIndex].getBalance()));
该代码仅在我删除该行的这一部分时运行:+Double.toString(user[currentIndex].getBalance())
我也尝试使用+user[currentIndex].getBalance()
,代码将无法运行。
那么如何才能使它在标签文本290.00
下面显示像Your current balance(RM):
(double type)这样的值?
如果user.getBalance()
返回原始double
或Double
,则以下内容应该有效:
Label balanceInfo = new Label("Your current balance (RM) :" + user[currentIndex].getBalance());
正如评论中所指出的,you should not use double
存储货币,但例如BigDecimal
。使用BigDecimal
,上面的代码仍然有效,或者格式化为货币:
Label balanceInfo = new Label("Your current balance (RM) :" +
NumberFormat.getCurrencyInstance().format(user[currentIndex].getBalance()));
例:
BigDecimal money = new BigDecimal(2345.856);
Label label = new Label("Your balance: " + NumberFormat.getCurrencyInstance().format(money));
将产生一个像Label
:
使用DecimalFormat类。
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(user[currentIndex].getBalance()));