Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions java/src/org/openqa/selenium/json/JsonInput.java
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,12 @@ public Number nextNumber() {
} while (true);

try {
Number number = new BigDecimal(builder.toString());
if (fractionalPart) {
BigDecimal number = new BigDecimal(builder.toString());
if (fractionalPart || number.stripTrailingZeros().scale() > 0) {
return number.doubleValue();
} else {
return number.longValueExact();
}
return number.longValue();
} catch (NumberFormatException e) {
throw new JsonException("Unable to parse to a number: " + builder + ". " + input);
}
Expand Down
17 changes: 17 additions & 0 deletions java/test/org/openqa/selenium/json/JsonInputTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ void shouldParseNonDecimalNumbersAsLongs() {
}
}

@Test
void shouldParseNonDecimalNumbersWithExponentAsLongs() {
try (JsonInput input = newInput("42e+1")) {
assertThat(input.peek()).isEqualTo(NUMBER);
assertThat(input.nextNumber()).isEqualTo(420L);
}
}

@Test
void shouldParseDecimalNumbersAsDoubles() {
try (JsonInput input = newInput("42.0")) {
Expand All @@ -79,6 +87,15 @@ void shouldParseDecimalNumbersAsDoubles() {
}
}

@Test
void shouldParseDecimalNumbersWithExponentAsDoubles() {
try (JsonInput input = newInput("42e-1")) {
assertThat(input.peek()).isEqualTo(NUMBER);
Number x = input.nextNumber();
assertThat((Double) x).isEqualTo(4.2d);
}
}

@Test
void shouldHandleNullValues() {
try (JsonInput input = newInput("null")) {
Expand Down
11 changes: 11 additions & 0 deletions java/test/org/openqa/selenium/json/JsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ void canReadANumber() {
assertThat((Number) new Json().toType("42", Number.class)).isEqualTo(42L);
assertThat((Integer) new Json().toType("42", Integer.class)).isEqualTo(42);
assertThat((Double) new Json().toType("42", Double.class)).isEqualTo(42.0);

assertThat((Double) new Json().toType("4.2e+1", Double.class)).isEqualTo(42.0);
assertThat((Integer) new Json().toType("4.2e+1", Integer.class)).isEqualTo(42);
assertThat((Long) new Json().toType("4.2e+1", Long.class)).isEqualTo(42L);

assertThat((Double) new Json().toType("42e+1", Double.class)).isEqualTo(420.0);
assertThat((Integer) new Json().toType("42e+1", Integer.class)).isEqualTo(420);
assertThat((Long) new Json().toType("42e+1", Long.class)).isEqualTo(420L);

assertThat((Double) new Json().toType("42e-1", Double.class)).isEqualTo(4.2);
assertThat((Double) new Json().toType("4.2e-1", Double.class)).isEqualTo(0.42);
}

@Test
Expand Down