Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# creating a calculator application - need some math help

charlie mills
Ranch Hand
Posts: 49
I've created buttons that add, subtract, multiply and divide and these work fine.

I now need to add squared, cubed and sqaure root.

For the sqaured button, I wrote this but it's not working:

int total = totalsofar^2

what am i doing wrong?

also, how would i sqaure root?

charlie mills
Ranch Hand
Posts: 49
i've just discovered the Math class so I have answered my own questions there. However, now I have a new question

I previously had all my values stored as integers and then decided that I needed them stored as doubles.

so at the moment i have:
I'm not really sure how to describe it, but is it because I'm reading in Integers from the string? i'm unsure of how to get it to read in the decimals.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
You can use "Double.parseDouble()" instead of "Integer.parseInt()".

Bauke Scholtz
Ranch Hand
Posts: 2458
To warn, do not use floating points when doing precise arithmetic calculations. Use BigDecimal.

Also see http://docs.sun.com/source/806-3568/ncg_goldberg.html

Campbell Ritchie
Sheriff
Posts: 50702
83
If you look here, you find the ^ operator does something completely different from what you thought.

Rob Spoor
Sheriff
Posts: 20709
68
Math has a method called pow that does what you think ^ does. Or, for squares and cubes, simply calculate "totalsofar * totalsofar" or "totalsofar * totalsofar * totalsofar".

Campbell Ritchie
Sheriff
Posts: 50702
83
Calculators are never really precise; you can use a double, knowing that the imprecision will be slight. If you do get \$1.10 - \$0.99 = \$0.109999999999999983465092374625 or similar, will that actually cause any problems?

Rob Spoor
Sheriff
Posts: 20709
68