0

Im having a problem with an app i want to create. It's about counting money you spent. I made a button. every time i press it the number of article x is increased by one. Just to test the whole thing, i set the price for the article on 0,3€. Above and below the button the number of articles and the money spent on them is displayed. I click the button, the money gets set to 0.3. I press again, and it gets set to 0.6. When I then press the third time, it doesnt say 0.9 but 0.89999999? Why doesent it just go to 0.9? I already tried rounding the whole thing but it doesnt work or my app just crashes... Maybe the mistake is really stupid but im kinda new to programming with Android Studio/Java and at this point im kinda stuck right now. Heres the piece of code im talking about:

TextView numbertextview;
TextView moneytextview;
Button addbutton;
double price, money;
int number;

...

    money = 0;
    moneytextview.setText(Double.toString(money));
    price = 0.3;
    number = 0;
    numbertextview.setText(Integer.toString(number));

    addbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            number++;
            numbertextview.setText(Integer.toString(number));

            money = money + price;
            moneytextview.setText(Double.toString(money) + "0€");

        }
    });
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Have u tried using decimal format – sdfbhg Nov 02 '17 at 18:01
  • Yeah i tried, but it either crashed or didnt change anything... – Felix Forster Nov 02 '17 at 18:14
  • Use BigDecimal for monetary calculations rather than double - https://stackoverflow.com/questions/1359817/using-bigdecimal-to-work-with-currencies – Michael Peacock Nov 02 '17 at 18:27
  • You can no more represent 0.1 exactly in binary than you can 1/3 in decimal. Every programmer needs to know how floating point numbers work. – duffymo Nov 02 '17 at 18:27
  • To avoid roundoff errors when using money, store the value in a long int as the number of cents, rather than in a float or double as the value in dollars. – FredK Nov 02 '17 at 18:41

1 Answers1

0

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

 moneytextview.setText(String.format("%.2f", Double.toString(money)) + "0€");

That should make it look right but, you may get rounding errors so be aware of that.

This question has sorta been answered in the other many questions about this silly computer memory problem with floats. However, as a new programmer who is trying to learn to code PrintF and formatting the float/double to look the way you want is more important than understanding why it's happening. Also, this question might have been answered in Double decimal formatting in Java more specifically.

Byrd
  • 325
  • 1
  • 8