String.toFloat
func String.toFloat(s: string): float64 | nullString.toFloat parses s as a decimal number, or returns null when it is not one. s is ASCII digits with an optional sign, fraction after ., and exponent after e or E; the result is rounded to the nearest float64 keeping the sign, so "-0" is -0.0, and a value beyond its range is null. It also reads NaN, and Inf or Infinity with an optional sign, in any case, so what String.from writes reads back. White space, _, and a prefix such as 0x are not numbers.
Details
- Reads ASCII digits with an optional sign, fraction, and exponent, so
.5and5.are numbers. It also readsNaN,Inf, andInfinity, in any case. - Anything else is
null: white space,_,,, a prefix such as0x, and digits of other scripts. - A value beyond the range of
float64isnull, not an infinity; a value too small to represent is0.0.
Basic examples
Parse a decimal number:
String.toFloat("3.14") // 3.14
String.toFloat("-1.5") // -1.5A string that is not a number gives null:
String.toFloat("abc") // nullSupply a default with ??:
String.toFloat("n/a") ?? 0.0 // 0.0Scope
A whole number becomes a float64; a leading + and leading zeros are allowed:
String.toFloat("42") // 42.0
String.toFloat("+7") // 7.0
String.toFloat("00012") // 12.0Either side of the . may be missing, but not both:
String.toFloat(".5") // 0.5
String.toFloat("5.") // 5.0
String.toFloat(".") // nullAn exponent follows e or E, with its own optional sign, and needs at least one digit:
String.toFloat("1e+3") // 1000.0
String.toFloat("2.5E-2") // 0.025
String.toFloat("1e") // null
String.toFloat("e5") // nullNaN and the infinities are read in any case, and Inf is short for Infinity:
String.toFloat("NaN") // NaN
String.toFloat("inf") // Infinity
String.toFloat("-INF") // -Infinity
String.toFloat("+Infinity") // InfinityString.from writes negative zero as -0.0, and it reads back with its sign:
String.toFloat("-0.0") // -0.0The result is the nearest float64. A value too small to represent rounds to 0.0, and a value beyond the range of float64 is null:
String.toFloat("18014398509481985") // 18014398509481984.0
String.toFloat("1e-400") // 0.0
String.toFloat("1e400") // nullThe empty string, white space, _, ,, and prefixes are not numbers:
String.toFloat("") // null
String.toFloat(" 1") // null
String.toFloat("1_000") // null
String.toFloat("1,5") // null
String.toFloat("0x10") // nullOnly ASCII digits count, so an Arabic-Indic digit or the minus sign − (U+2212) gives null:
String.toFloat("٣") // null
String.toFloat("−1") // nullThe result is always float64; convert it to get a float32:
float32(String.toFloat("1.5") ?? 0.0) // 1.5Call it with a named argument, or in a pipe:
String.toFloat(s: "3.25") // 3.25
"2.5" | String.toFloat() // 2.5Applications
Sum the numeric fields of a line and count the ones that do not parse. Narrow with != null to use the number:
let line = "3.5, 2, oops, 1e1"
var total = 0.0
var bad = 0
for field in line.split(",") {
let n = field.trim().toFloat()
if n != null {
total += n
} else {
bad += 1
}
}
println("total ${total}, ${bad} bad")total 15.5, 1 badRead a setting with a fallback when it is missing or malformed:
let settings = Map{ "ratio": "0.75", "scale": "big" }
func setting(name: string, fallback: float64): float64 {
settings[name]?.toFloat() ?? fallback
}
println(setting("ratio", 1.0))
println(setting("scale", 1.0))
println(setting("depth", 2.0))0.75
1.0
2.0Validate a whole column with Array.every:
let column = ["1.5", "2", "-0.25"]
column.every({ x.toFloat() != null }) // trueProperties and relations
String.toFloat reads back what String.from writes, for every finite value and the infinities:
for x in [0.1 + 0.2, -1.5, 1e21, 5e-324, 1.7976931348623157e308, Math.Infinity, -Math.Infinity] {
assert(String.from(x).toFloat() == x)
}NaN reads back too, but NaN never equals itself, so test it with Math.isNaN:
let n = String.from(Math.NaN).toFloat()
assert(n != null && Math.isNaN(n))For an integer that fits, it agrees with String.toInt and a conversion:
for s in ["0", "-17", "123456"] {
assert(s.toFloat() == float64(s.toInt() ?? 0))
}It reads what String.fromFloat writes, up to the rounding fromFloat applies:
String.fromFloat(2.675, 2).toFloat() // 2.67Possible issues
The result can be null, so arithmetic on it does not compile until you remove the null:
let x = String.toFloat("1.5") * 2.0
// error: * needs both operands of one type, got float64 | null and float64(String.toFloat("1.5") ?? 0.0) * 2.0 // 3.0Surrounding white space makes the whole string invalid. Trim it first with String.trim:
String.toFloat(" 2.5\n") // null
String.toFloat(" 2.5\n".trim()) // 2.5A number beyond the range of float64 is null, not Infinity, so you cannot tell it from text that is not a number:
String.toFloat("1e309") // null
String.toFloat("Infinity") // Infinity"NaN" parses, so a parsed value can still be NaN. It compares unequal to everything, itself included:
let v = String.toFloat("nan") ?? 0.0
v == v // falseA large integer loses precision as a float64. Use String.toInt when you need the exact integer:
String.toFloat("18014398509481985") // 18014398509481984.0
String.toInt("18014398509481985") // 18014398509481985See also
String.toIntandString.toUintparse integers.String.fromwrites a float thatString.toFloatreads back.String.fromFloatwrites a float in fixed point.Math.isNaNtests forNaN.
