JackyBoi
JackyBoi

Reputation: 2773

dealing with money and Big Decimal

I am trying to write a program that stores money in a variable, so I am using Bigdecimal type as it was advised by other memebers here.. But what I am trying to do is this.. user can type in what ever way he wants means to say, he can type

 24
 or
 24.0
 or
 24.00

so as you can see that I am giving the user flexibility to type at his own convenience. But in the end the variable will be stored in an array (BigDecimal array) so when it stores I want to store with and only 2decimal places. Why I say that is if the user types in 24 I want to store 24.00 NOT 24 or 24.0 JUST 24.00 or if he enters 24.00 then that will be stored with out any modification done to it.. how to do this.. Sample code provided below.

    BigDecimal bala;
    BigDecimal balintake;
    static BigDecimal[] bal= new BigDecimal[20];
    Scanner sc = new Scanner(System.in);
    balintake = sc.nextBigDecimal();

     bala.setScale(2,RoundingMode.HALF_UP);
     bal[0] = bala;

But this is not working as according to my requirements.

Upvotes: 1

Views: 336

Answers (3)

allotria
allotria

Reputation: 191

Remember that BigDecimal objects are immutable. So, when you do

balintake.setScale(2,RoundingMode.HALF_UP);

you should assign it to back to a variable, like

balintake = balintake.setScale(2,RoundingMode.HALF_UP);

Upvotes: 4

Transcendence
Transcendence

Reputation: 2706

For starters, you never initialized the variable "bala"

So you set "balintake" to be the Scanner's next big decimal. The "setScale" method doesn't change the BigDecimal itself since BigDecimals are immutable, it returns a new BigDecimal with the scale set.

I believe this is what you want:

BigDecimal balintake;
BigDecimal[] bal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
balintake = sc.nextBigDecimal();

balintake = balintake.setScale(2,RoundingMode.HALF_UP);
bal[0] = balintake;

Upvotes: 0

Lauri Piispanen
Lauri Piispanen

Reputation: 2097

java.math.BigDecimal.setScale(int) returns a new BigDecimal instead of mutating the original one.

Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

Upvotes: 2

Related Questions