Skip to content

Commit 9c63b3a

Browse files
committed
#81 - Add the missing toFloat() toDouble() type conversion methods
These are used for query parameters allowing null/empty values (as opposed to `asFloat()` which does not allow nulls).
1 parent 6fad506 commit 9c63b3a

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

http-api/src/main/java/io/avaje/http/api/PathTypeConversion.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,33 @@ public static Long toLong(String value) {
228228
}
229229
}
230230

231+
/**
232+
* Convert to Double (allowing nulls).
233+
*/
234+
public static Double toDouble(String value) {
235+
if (isNullOrEmpty(value)) {
236+
return null;
237+
}
238+
try {
239+
return Double.valueOf(value);
240+
} catch (NumberFormatException e) {
241+
throw new InvalidTypeArgumentException(e);
242+
}
243+
}
244+
/**
245+
* Convert to Float (allowing nulls).
246+
*/
247+
public static Float toFloat(String value) {
248+
if (isNullOrEmpty(value)) {
249+
return null;
250+
}
251+
try {
252+
return Float.valueOf(value);
253+
} catch (NumberFormatException e) {
254+
throw new InvalidTypeArgumentException(e);
255+
}
256+
}
257+
231258
/**
232259
* Convert to BigDecimal (allowing nulls).
233260
*/

http-api/src/test/java/io/avaje/http/api/PathTypeConversionTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,28 @@ void toLong_invalid() {
252252
assertThrows(InvalidTypeArgumentException.class, () -> PathTypeConversion.toLong("junk"));
253253
}
254254

255+
@Test
256+
void toDouble() {
257+
assertThat(PathTypeConversion.toDouble("42")).isEqualTo(42D);
258+
assertThat(PathTypeConversion.toDouble(null)).isNull();
259+
}
260+
261+
@Test
262+
void toDouble_invalid() {
263+
assertThrows(InvalidTypeArgumentException.class, () -> PathTypeConversion.toDouble("junk"));
264+
}
265+
266+
@Test
267+
void toFloat() {
268+
assertThat(PathTypeConversion.toFloat("42")).isEqualTo(42F);
269+
assertThat(PathTypeConversion.toFloat(null)).isNull();
270+
}
271+
272+
@Test
273+
void toFloat_invalid() {
274+
assertThrows(InvalidTypeArgumentException.class, () -> PathTypeConversion.toFloat("junk"));
275+
}
276+
255277
@Test
256278
void toBigDecimal() {
257279
assertThat(PathTypeConversion.toBigDecimal("42.45")).isEqualByComparingTo("42.45");

0 commit comments

Comments
 (0)