parseOrNull

fun parseOrNull(value: String): Decimal?

Returns a Decimal representing the number described by value, or returns null if value doesn't represent a decimal number.

A valid decimal representation is defined as:

decimal = [sign] digit {digit} ['.' digit {digit}]
sign = "+" | "-"
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

(grammar written in Wirth-style EBNF, where [] denotes optionality and {} denotes repetition)

Leading zeros, leading plus sign, and trailing fractional zeros are ignored when interpreting value. As a result, calling this function with 3.14, +03.140, and 3.14000 produces the same decimal.


Calling from Kotlin

Here's an example of calling this function from Kotlin code:

fun parsesTo(input: String, expected: String) {
check(Decimal.parse(input).toString() == expected)
check(Decimal.parseOrNull(input).toString() == expected)
}

fun parsingFailsWith(input: String) {
val exception: Throwable? = runCatching { Decimal.parse(input) }
.exceptionOrNull()
check(exception is NumberFormatException)
check(Decimal.parseOrNull(input) == null)
}

// Parsing normalizes zero:
parsesTo(input = "0", expected = "0")
parsesTo(input = "+0", expected = "0")
parsesTo(input = "-0", expected = "0")
parsesTo(input = "0.0", expected = "0")
parsesTo(input = "-0.0", expected = "0")

// Parsing removes leading plus sign:
parsesTo(input = "+3.14", expected = "3.14")

// Parsing removes leading zeros:
parsesTo(input = "00042", expected = "42")
parsesTo(input = "-00042", expected = "-42")

// Parsing removes trailing fractional zeros:
parsesTo(input = "3.10", expected = "3.1")
parsesTo(input = "5.00", expected = "5")

// Parsing preserves canonical representation:
parsesTo(input = "3.14", expected = "3.14")
parsesTo(input = "-2.5", expected = "-2.5")
parsesTo(input = "0.001", expected = "0.001")

// Parsing fails with non-decimal string:
parsingFailsWith("")
parsingFailsWith("+")
parsingFailsWith("-")
parsingFailsWith(".")
parsingFailsWith(".5")
parsingFailsWith("3.")
parsingFailsWith("1.2.3")
parsingFailsWith("1.5E3")
parsingFailsWith("12a")

This function is hidden from Java, because nullability is not explicit in its type system.

See the parse function for throwing an exception instead of returning null in case of invalid value.