fix: handling of double and integer (#316)

Signed-off-by: apulbere <apulbere@yahoo.com>
This commit is contained in:
apulbere 2023-03-08 15:49:05 +02:00 committed by GitHub
parent 09824e7c52
commit 0a27a77fc1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 16 deletions

View File

@ -56,12 +56,13 @@ public interface Structure {
return value.asBoolean();
}
if (value.isNumber()) {
Double valueAsDouble = value.asDouble();
if (valueAsDouble == Math.floor(valueAsDouble) && !Double.isInfinite(valueAsDouble)) {
return value.asInteger();
if (value.isNumber() && !value.isNull()) {
Number numberValue = (Number) value.asObject();
if (numberValue instanceof Double) {
return numberValue.doubleValue();
} else if (numberValue instanceof Integer) {
return numberValue.intValue();
}
return valueAsDouble;
}
if (value.isString()) {

View File

@ -35,8 +35,7 @@ public class Value implements Cloneable {
* (boolean, string, int, double, list, structure, instant)
*/
public Value(Object value) throws InstantiationException {
// integer is a special case, convert those.
this.innerObject = value instanceof Integer ? ((Integer)value).doubleValue() : value;
this.innerObject = value;
if (!this.isNull()
&& !this.isBoolean()
&& !this.isString()
@ -61,7 +60,7 @@ public class Value implements Cloneable {
}
public Value(Integer value) {
this.innerObject = value.doubleValue();
this.innerObject = value;
}
public Value(Double value) {
@ -113,7 +112,7 @@ public class Value implements Cloneable {
* @return boolean
*/
public boolean isNumber() {
return this.innerObject instanceof Double;
return this.innerObject instanceof Number;
}
/**
@ -187,8 +186,8 @@ public class Value implements Cloneable {
* @return Integer
*/
public Integer asInteger() {
if (this.isNumber()) {
return (int)Math.round((Double)this.innerObject);
if (this.isNumber() && !this.isNull()) {
return ((Number)this.innerObject).intValue();
}
return null;
}
@ -199,8 +198,8 @@ public class Value implements Cloneable {
* @return Double
*/
public Double asDouble() {
if (this.isNumber()) {
return (Double)this.innerObject;
if (this.isNumber() && !isNull()) {
return ((Number)this.innerObject).doubleValue();
}
return null;
}

View File

@ -66,11 +66,11 @@ public class ValueTest {
}
@Test public void numericArgShouldReturnDoubleOrInt() {
double innerDoubleValue = .75;
double innerDoubleValue = 1.75;
Value doubleValue = new Value(innerDoubleValue);
assertTrue(doubleValue.isNumber());
assertEquals(1, doubleValue.asInteger()); // should be rounded
assertEquals(.75, doubleValue.asDouble());
assertEquals(1, doubleValue.asInteger()); // the double value represented by this object converted to type int
assertEquals(1.75, doubleValue.asDouble());
int innerIntValue = 100;
Value intValue = new Value(innerIntValue);