scoop:scoop.std:0.1.0
src/text/floating_text.scoop
Selected production source · src/text/floating_text.scoop
1
package scoop.text3
/**4
* Parses a decimal Float or the exact NaN/Infinity spellings. Malformed input or finite overflow5
* returns None.6
*/7
public fun String.toFloatOrNone(): Float? {8
if (this == "NaN") return Some(Float.NaN)9
if (this == "Infinity" || this == "+Infinity") return Some(Float.POSITIVE_INFINITY)10
if (this == "-Infinity") return Some(Float.NEGATIVE_INFINITY)11
val rounded = when (roundDecimal(this, 24L, -149L, -46L, 38L)) {12
case None -> return None13
case Some(val value) -> value14
}15
var scale = 1f16
var exponent = rounded.exponent17
while (exponent < 0L) { scale /= 2f; exponent += 1L }18
while (exponent > 0L) { scale *= 2f; exponent -= 1L }19
val value = rounded.significand.toFloat() * scale20
if (!value.isFinite()) return None21
return Some(if (rounded.negative) -value else value)22
}24
/**25
* Parses a decimal Double or the exact NaN/Infinity spellings. Malformed input or finite overflow26
* returns None.27
*/28
public fun String.toDoubleOrNone(): Double? {29
if (this == "NaN") return Some(Double.NaN)30
if (this == "Infinity" || this == "+Infinity") return Some(Double.POSITIVE_INFINITY)31
if (this == "-Infinity") return Some(Double.NEGATIVE_INFINITY)32
val rounded = when (roundDecimal(this, 53L, -1074L, -324L, 308L)) {33
case None -> return None34
case Some(val value) -> value35
}36
var scale = 1.037
var exponent = rounded.exponent38
while (exponent < 0L) { scale /= 2.0; exponent += 1L }39
while (exponent > 0L) { scale *= 2.0; exponent -= 1L }40
val value = rounded.significand.toDouble() * scale41
if (!value.isFinite()) return None42
return Some(if (rounded.negative) -value else value)43
}45
/**46
* Parses a decimal Float or the exact NaN/Infinity spellings; invalid input throws47
* NumberFormatException.48
*/49
public fun String.toFloat(): Float = requireParsedNumber<Float>(toFloatOrNone())50
/**51
* Parses a decimal Double or the exact NaN/Infinity spellings; invalid input throws52
* NumberFormatException.53
*/54
public fun String.toDouble(): Double = requireParsedNumber<Double>(toDoubleOrNone())