在JavaFX中将double类型值从变量更改为String / text输出?

时间:2017-12-14 06:28:07

标签: java javafx javafx-8 currency

我有一个双重类型的值,我从另一个名为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):(双重类型)的值?

2 个答案:

答案 0 :(得分:3)

如果user.getBalance()返回原始doubleDouble,则以下内容应该有效:

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之类的:

enter image description here

答案 1 :(得分:0)

使用DecimalFormat类。

DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(user[currentIndex].getBalance()));