Zulip Chat Archive

Stream: lean4

Topic: extract float from string?


Robert (Apr 04 2025 at 06:30):

hey everyone! How do we extract a float value from the string? Theres functions like "String.toInt?" but i dont see a similar one for float?

Jovan Gerbscheid (Apr 04 2025 at 10:07):

I guess the best you can do is use docs#OfScientific.ofScientific, and parse the exact numbers from the String yourself.

Mario Carneiro (Apr 04 2025 at 19:19):

there is definitely a float parser in core, it is needed in JSON parsing

Mario Carneiro (Apr 04 2025 at 19:30):

It produces JsonNumber but it's not too hard to adapt it

import Lean.Data.Json.Parser
import Batteries.Lean.Float

def String.toFloat? (s : String) : Option Float := do
  let { mantissa, exponent }  (Lean.Json.Parser.num.run s).toOption
  return Int.divFloat mantissa (10 ^ exponent)

/-- info: some 2.000000 -/
#guard_msgs in #eval String.toFloat? "2.0"
/-- info: some 0.000023 -/
#guard_msgs in #eval String.toFloat? "2.333333e-5"
/-- info: none -/
#guard_msgs in #eval String.toFloat? "hello"

Kim Morrison (Apr 06 2025 at 00:16):

Perhaps someone could refactor that flip the dependency (i.e. keep the same logic, but in a new Float.fromString? and have the json parser call that?

Mario Carneiro (Apr 06 2025 at 00:31):

well you probably wouldn't want to have json route through floats directly as the process is lossy

Mario Carneiro (Apr 06 2025 at 00:31):

currently it's being parsed into JsonNumber which can represent decimal fractions losslessly

Mario Carneiro (Apr 06 2025 at 00:32):

but you could have a more agnostic basic function which returns the mantissa/exponent components without committing to the JsonNumber type

Mario Carneiro (Apr 06 2025 at 00:33):

(Note also that I used a function from batteries here (Int.divFloat), which as you can tell from the module name I'm :+1: on upstreaming)


Last updated: May 02 2025 at 03:31 UTC