[Wasm] Fix stdlib String to Float parse

This commit is contained in:
Igor Yakovlev
2022-12-19 18:39:01 +01:00
committed by teamcity
parent 8b14f4b15c
commit 35340f2f04
2 changed files with 26 additions and 3 deletions
@@ -154,6 +154,27 @@ class StringNumberConversionTest {
}
}
@Test fun toFloat() {
compareConversion(String::toFloat, String::toFloatOrNull, ::floatTotalOrderEquals) {
assertProduces("-77", -77.0f)
assertProduces("77.", 77.0f)
assertProduces("77.0", 77.0f)
assertProduces("-1.77", -1.77f)
assertProduces("+.77", 0.77f)
assertProduces("\t-77 \n", -77.0f)
assertProduces("7.7e1", 77.0f)
assertProduces("+770e-1", 77.0f)
assertProduces("-NaN", -Float.NaN)
assertProduces("+Infinity", Float.POSITIVE_INFINITY)
assertFailsOrNull("7..7")
assertFailsOrNull("007 not a number")
assertFailsOrNull("")
assertFailsOrNull(" ")
}
}
@Test fun toUByte() {
@@ -408,6 +429,8 @@ class StringNumberConversionTest {
internal fun doubleTotalOrderEquals(a: Double?, b: Double?): Boolean = (a as Any?) == b
internal fun floatTotalOrderEquals(a: Float?, b: Float?): Boolean = (a as Any?) == b
internal fun <T : Any> compareConversion(
convertOrFail: (String) -> T,
convertOrNull: (String) -> T?,
@@ -6,7 +6,7 @@
package kotlin.text
import kotlin.math.abs
import kotlin.wasm.internal.wasm_f32_demote_f64
/**
* Returns `true` if the content of this string is equal to the word "true", ignoring case, and `false` otherwise.
*/
@@ -84,13 +84,13 @@ public actual fun String.toDouble(): Double = kotlin.text.parseDouble(this)
* Parses the string as a [Float] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public actual fun String.toFloat(): Float = toDouble() as Float
public actual fun String.toFloat(): Float = wasm_f32_demote_f64(toDouble())
/**
* Parses the string as a [Float] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
public actual fun String.toFloatOrNull(): Float? = toDoubleOrNull() as Float?
public actual fun String.toFloatOrNull(): Float? = toDoubleOrNull()?.let { wasm_f32_demote_f64(it) }
/**
* Parses the string as a [Double] number and returns the result