Scoop API

scoop:scoop.std:0.1.0

src/text/floating_text.scoop

Selected production source · src/text/floating_text.scoop

1package scoop.text
3/**
4 * Parses a decimal Float or the exact NaN/Infinity spellings. Malformed input or finite overflow
5 * returns None.
6 */
7public 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 None
13 case Some(val value) -> value
14 }
15 var scale = 1f
16 var exponent = rounded.exponent
17 while (exponent < 0L) { scale /= 2f; exponent += 1L }
18 while (exponent > 0L) { scale *= 2f; exponent -= 1L }
19 val value = rounded.significand.toFloat() * scale
20 if (!value.isFinite()) return None
21 return Some(if (rounded.negative) -value else value)
24/**
25 * Parses a decimal Double or the exact NaN/Infinity spellings. Malformed input or finite overflow
26 * returns None.
27 */
28public 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 None
34 case Some(val value) -> value
35 }
36 var scale = 1.0
37 var exponent = rounded.exponent
38 while (exponent < 0L) { scale /= 2.0; exponent += 1L }
39 while (exponent > 0L) { scale *= 2.0; exponent -= 1L }
40 val value = rounded.significand.toDouble() * scale
41 if (!value.isFinite()) return None
42 return Some(if (rounded.negative) -value else value)
45/**
46 * Parses a decimal Float or the exact NaN/Infinity spellings; invalid input throws
47 * NumberFormatException.
48 */
49public fun String.toFloat(): Float = requireParsedNumber<Float>(toFloatOrNone())
50/**
51 * Parses a decimal Double or the exact NaN/Infinity spellings; invalid input throws
52 * NumberFormatException.
53 */
54public fun String.toDouble(): Double = requireParsedNumber<Double>(toDoubleOrNone())