1 package net.sf.openrocket.unit;
3 import net.sf.openrocket.util.MathUtil;
6 * An immutable class representing an SI value and a unit. The toString() method yields the
7 * current value in the current units. This class may be used to encapsulate
8 * a sortable value for example for tables. The sorting is performed by the
9 * value in the current units, ignoring the unit.
11 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
13 public class Value implements Comparable<Value> {
15 private final double value;
16 private final Unit unit;
20 * Create a new Value object.
22 * @param value the value to set.
23 * @param unit the unit to set (<code>null</code> not allowed)
25 public Value(double value, Unit unit) {
27 throw new IllegalArgumentException("unit is null");
35 * Creates a new Value object using unit group. Currently it simply uses the default
36 * unit of the group, but may later change.
38 * @param value the value to set.
39 * @param group the group the value belongs to.
41 public Value(double value, UnitGroup group) {
42 this(value, group.getDefaultUnit());
47 * Get the value of this object (in SI units).
51 public double getValue() {
58 * Get the value of this object in the current units.
60 * @return the value in the current units.
62 public double getUnitValue() {
63 return unit.toUnit(value);
68 * Get the unit of this object.
72 public Unit getUnit() {
78 * Return a string formatted using the {@link Unit#toStringUnit(double)} method
79 * of the current unit. If the unit is <code>null</code> then the UNITS_NONE
83 public String toString() {
84 return unit.toStringUnit(value);
90 public boolean equals(Object obj) {
95 if (getClass() != obj.getClass())
98 Value other = (Value) obj;
99 if (this.unit != other.unit) {
103 if (!MathUtil.equals(this.value, other.value)) {
112 public int hashCode() {
113 final int prime = 31;
115 result = prime * result + ((unit == null) ? 0 : unit.hashCode());
117 temp = Double.doubleToLongBits(value);
118 result = prime * result + (int) (temp ^ (temp >>> 32));
124 * Compare this value to another value. The comparison is performed primarily by
125 * the unit text, secondarily the value in the unit values.
128 public int compareTo(Value o) {
129 int n = this.getUnit().getUnit().compareTo(o.getUnit().getUnit());
133 double us = this.getUnitValue();
134 double them = o.getUnitValue();
136 if (Double.isNaN(us)) {
137 if (Double.isNaN(them))
142 if (Double.isNaN(them))