1 | /** |
---|
2 | * Created on 2008-01-05 |
---|
3 | */ |
---|
4 | package simulator.utils; |
---|
5 | |
---|
6 | import java.math.BigDecimal; |
---|
7 | import java.text.DecimalFormat; |
---|
8 | import java.util.Locale; |
---|
9 | |
---|
10 | /** |
---|
11 | * This class provides basic mathematical operations for the <code>double</code> primitive type |
---|
12 | * @author Stanislaw Szczepanowski |
---|
13 | */ |
---|
14 | public class DoubleMath { |
---|
15 | |
---|
16 | /** |
---|
17 | * The pattern used for converting a <code>double</code> value to a string |
---|
18 | */ |
---|
19 | public static String PATTERN = "###.###"; |
---|
20 | |
---|
21 | /** |
---|
22 | * A protected constructor which will be invoked only |
---|
23 | * one time in the lifetime of this class |
---|
24 | */ |
---|
25 | protected DoubleMath() { |
---|
26 | } |
---|
27 | |
---|
28 | /** |
---|
29 | * Adds two <code>double</code> values and returns the result of addition |
---|
30 | * @param left the left argument |
---|
31 | * @param right the right argument |
---|
32 | * @return the result of addition of the two arguments |
---|
33 | */ |
---|
34 | public static double add(double left, double right) { |
---|
35 | DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH); |
---|
36 | df.applyPattern(PATTERN); |
---|
37 | String leftStr = df.format(left); |
---|
38 | String rightStr = df.format(right); |
---|
39 | BigDecimal resultDec = new BigDecimal(leftStr); |
---|
40 | BigDecimal rightDec = new BigDecimal(rightStr); |
---|
41 | resultDec = resultDec.add(rightDec); |
---|
42 | return resultDec.doubleValue(); |
---|
43 | } |
---|
44 | |
---|
45 | /** |
---|
46 | * Subtracts from the <code>left</code> argument the <code>right</code> argument and returns the result of subtraction |
---|
47 | * @param left the left argument |
---|
48 | * @param right the right argument |
---|
49 | * @return the result of subtraction of the two arguments |
---|
50 | */ |
---|
51 | public static double subtract(double left, double right) { |
---|
52 | DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH); |
---|
53 | df.applyPattern(PATTERN); |
---|
54 | String leftStr = df.format(left); |
---|
55 | String rightStr = df.format(right); |
---|
56 | BigDecimal resultDec = new BigDecimal(leftStr); |
---|
57 | BigDecimal rightDec = new BigDecimal(rightStr); |
---|
58 | resultDec = resultDec.subtract(rightDec); |
---|
59 | return resultDec.doubleValue(); |
---|
60 | } |
---|
61 | |
---|
62 | } |
---|