# Percentage of a Double

• 02-14-2014, 07:15 PM
chaoticcircuit
Percentage of a Double
Very basic question , here..

Code:

```double Compact=30.50; double Full=40.50; double discount=.07; double FullDiscount= 37.67; double CompactDiscount= 28.37;```
My question is how do I configure this so that when / if I need to change the discount value, it automatically adjusts the % discount off of the Full or Compact?

All I can get to work is simply hardcoding it and assigning the discount value, i'm probably just messing up the syntax.

• 02-14-2014, 07:53 PM
jim829
Re: Percentage of a Double
Do you mean something like this?

Code:

```double Compact=30.50; double Full=40.50; double discount=.07; double FullDiscount= Full * (1-discount); double CompactDiscount= Compact* (1-discount);```
Note that in the above case:

1. It does not work when you change the value during program execution.
2. Your precision will not be limited to two decimal places.

So you might want to encode this in a method where you can do some rounding (which has its own set of problems). Best to work in cents (US) or the minimal unit of currency in other locales. Then convert to dollars or euros, or whatever.

Regards,
Jim
• 02-14-2014, 08:43 PM
kjkrum
Re: Percentage of a Double
Your variable names suggest that you're dealing with money. You should read this: Java Practices -> Representing money
• 02-16-2014, 11:55 PM
chaoticcircuit
Re: Percentage of a Double
Quote:

Originally Posted by jim829
Do you mean something like this?

Code:

```double Compact=30.50; double Full=40.50; double discount=.07; double FullDiscount= Full * (1-discount); double CompactDiscount= Compact* (1-discount);```
Note that in the above case:

1. It does not work when you change the value during program execution.
2. Your precision will not be limited to two decimal places.

So you might want to encode this in a method where you can do some rounding (which has its own set of problems). Best to work in cents (US) or the minimal unit of currency in other locales. Then convert to dollars or euros, or whatever.

Regards,
Jim

Ironically enough, I figured this out before I checked back, but thanks very much Jim. This is exactly what I needed, as basic as that is. I used %.2f to keep it to only 2 decimals.