From 618b81da627b55dcb051d889c7faffd91804497a Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Tue, 4 Aug 2020 16:42:55 -0500 Subject: Added scientific rounding. --- src/org/unitConverter/unit/UnitDatabase.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'src/org/unitConverter/unit/UnitDatabase.java') diff --git a/src/org/unitConverter/unit/UnitDatabase.java b/src/org/unitConverter/unit/UnitDatabase.java index 0246630..c5432f7 100644 --- a/src/org/unitConverter/unit/UnitDatabase.java +++ b/src/org/unitConverter/unit/UnitDatabase.java @@ -21,6 +21,7 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.math.BigDecimal; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Arrays; @@ -1465,7 +1466,7 @@ public final class UnitDatabase { public LinearUnitValue evaluateUnitExpression(final String expression) { Objects.requireNonNull(expression, "expression must not be null."); - // attempt to get a unit as an alias first + // attempt to get a unit as an alias, or a number with precision first if (this.containsUnitName(expression)) return this.getLinearUnitValue(expression); @@ -1598,6 +1599,7 @@ public final class UnitDatabase { } else { // get a linear unit final Unit unit = this.getUnit(name); + if (unit instanceof LinearUnit) return (LinearUnit) unit; else @@ -1615,7 +1617,15 @@ public final class UnitDatabase { * @since 2020-08-04 */ private LinearUnitValue getLinearUnitValue(final String name) { - return LinearUnitValue.getExact(this.getLinearUnit(name), 1); + try { + // try to parse it as a number - otherwise it is not a number! + final BigDecimal number = new BigDecimal(name); + + final double uncertainty = Math.pow(10, -number.scale()); + return LinearUnitValue.of(SI.ONE, number.doubleValue(), uncertainty); + } catch (final NumberFormatException e) { + return LinearUnitValue.getExact(this.getLinearUnit(name), 1); + } } /** @@ -1682,7 +1692,9 @@ public final class UnitDatabase { return SI.ONE.times(value); } catch (final NumberFormatException e) { final Unit unit = this.units.get(name); - if (unit.getPrimaryName().isEmpty()) + if (unit == null) + throw new NoSuchElementException("No unit " + name); + else if (unit.getPrimaryName().isEmpty()) return unit.withName(NameSymbol.ofName(name)); else if (!unit.getPrimaryName().get().equals(name)) { final Set otherNames = new HashSet<>(unit.getOtherNames()); -- cgit v1.2.3