Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# # opposite of

Evan Pierce
Ranch Hand

Joined: Jan 31, 2006
Posts: 36
im trying to take a double i have and put it into another double but have it be the opposite of the first double.
in example...
double A = 0.1
double B = ?opposite of? A

so B would be -0.1

whats the simplest way to do this?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24148

27

double B = -A;

People generally say "negative of", not "opposite of."

Evan Pierce
Ranch Hand

Joined: Jan 31, 2006
Posts: 36
ok but now what if i had
double A = -0.1
double B = ....( should be 0.1)
??
how would i make that into positive of?
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
how would i make that into positive of?
We're talking about negating numbers: so 0.1 negated becomes -0.1, while -0.1 negated becomes 0.1 (positive) just as in normal arithmetic. You can therefore just do this:But of course if we set A to be +0.1 then:If you want to guarantee that B is always positive (regardless of the sign of A), you'll want to take the mathematical modulus (absolute) value; you can do this using the abs() method in Math:

Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / Amazon Amazon UK )
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I grew up on some language or other that didn't allow a unary minus sign like that, so I still write:

b = 0 - a;

Do you find that any clearer?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi

I agree. Here's the link: http://aspose.com/file-tools

subject: # opposite of