2

I have a double type value that I call from another class named Account, and this value holds the balance, of a user. Everytime a user click a button, I want to put it on display. Something like this :

The value (taken from class Account) should be located and presented below Your current balance(RM):. But when I use the code below here, it won't even run the code.

Label balanceInfo = new Label("Your current balance (RM) :"+Double.toString(user[currentIndex].getBalance()));

The code only runs when I delete this part of the line : +Double.toString(user[currentIndex].getBalance()) I have also tried using +user[currentIndex].getBalance() , and the code won't run.

So how do I make it so that it can show the value like 290.00 (double type) below the Label text Your current balance(RM): ?

DVarga
  • 21,311
  • 6
  • 55
  • 60
Lutfi
  • 131
  • 7

2 Answers2

3

If user.getBalance() returns a primitive double or a Double, then the following should work :

Label balanceInfo = new Label("Your current balance (RM) :" + user[currentIndex].getBalance());

As pointed out in the comment, you should not use double to store a currency, but for example a BigDecimal. With BigDecimal the code above will still work, or to format really as a currency:

Label balanceInfo = new Label("Your current balance (RM) :" + 
    NumberFormat.getCurrencyInstance().format(user[currentIndex].getBalance()));

Example:

BigDecimal money = new BigDecimal(2345.856);
Label label = new Label("Your balance: " + NumberFormat.getCurrencyInstance().format(money));

will produce a Label like:

enter image description here

DVarga
  • 21,311
  • 6
  • 55
  • 60
  • I never knew about this before. Does that mean I have to change my Account class data type (since the balance is taken from that class), or just in this GUI class? Thanks again. – Lutfi Dec 16 '17 at 06:56
  • As a general design rule, you should not store any data in the view, so yes, the Account data class should be changed. – DVarga Dec 16 '17 at 08:48
0

Use DecimalFormat class.

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