Search code examples
javabigdecimal

BigDecimal.scale(0) put in method call works in not an appropriat way


I have the method:

public void send(Player player, String sum) {
    Map<String, String> map = new HashMap<String, String>();
    addPlayerVariables(map, player);
    map.put("sum", sum);

    setVariableMap(map);

    setTemplateType(TemplateType.BIRTHDAY);
    sendMessage(player.getEmail());
}

and I call that method as follows:

send(player, newBonus.getBonusSum().setScale(0).toPlainString() + " " + account.getCurrency().getName());

and it works as if I ever didn't put the scale into getBonusSum(). For instance:

newBonus.getBonusSum().setScale(0).toPlainString() is 1500 newBonus.getBonusSum().toPlainString() is 1500.0000

and in the send() 1500.0000 is passed instead of 1500. Why?

But If I split that into:

String str = newBonus.getBonusSum().setScale(0).toPlainString();
send(player, str + " " + account.getCurrency().getName());

it works fine. Could someone explain the reason?


Solution

  • and it works as if I ever didn't put the scale into getBonusSum(). For instance:

    Because

    newBonus.getBonusSum().setScale(0)
    

    returns a new BigDecimal object
    When you invoke setScale method it returns a new BigDecimal object and it doesn't modify the existing object. So you need to re-assign it to newBonus like this

    newBonus = newBonus.getBonusSum().setScale(0);
    

    Updated To make it more clear ,Let say newBonus has a value 1500.0000 when you invoke

    newBonus.getBonusSum().setScale(0).toPlainString() 
    

    Then a new BigDecimal variable is created with value 1500.0000 and scale 0 and then you call toPlainString on it. Hence you see 1500
    After that you execute the following statement

    newBonus.getBonusSum().toPlainString()
    

    Which will print 1500.0000 because neither newBonus value nor its scale was modified. Hence you see 1500.0000