Zulip Chat Archive

Stream: lean4

Topic: String to Float


Charles Hughes (Sep 21 2021 at 06:28):

Is there some way to convert a String to a Float? I'm trying to take Floats as inputs to my binary

Charles Hughes (Sep 21 2021 at 06:30):

I see a toString for Float but no ofString

Charles Hughes (Sep 21 2021 at 06:31):

hm maybe passing the values via sci notation would be the easiest

Eric Wieser (Sep 21 2021 at 07:03):

Are you asking about #lean4?

Charles Hughes (Sep 21 2021 at 07:12):

yes

Notification Bot (Sep 21 2021 at 08:00):

This topic was moved here from #general > String to Float by Sebastian Ullrich

Christian Pehle (Sep 21 2021 at 09:49):

(deleted)

Siddhartha Gadgil (Sep 21 2021 at 12:54):

There are a couple of methods in Meta which may help: there is decodeScientificLitVal?which gives components and the typeclass OfScientific that has a float instance.

Siddhartha Gadgil (Sep 21 2021 at 12:58):

Here is an example:

def getFloat (s: String) : Option Float :=
  (Syntax.decodeScientificLitVal? s).map (fun m, s, e => Float.ofScientific m s e)

#eval getFloat "3.1415" -- gives some 3.141500

Mac (Sep 21 2021 at 15:40):

Here is a somewhat hacky solution that none-the-less gets the job done:

import Lean.Data.Json.Parser

open Lean in
def parse (s : String) : Except String Float :=
  match Json.Parser.num s.mkIterator with
  | Parsec.ParseResult.success _ res =>
    Except.ok <| Float.ofInt res.mantissa * 10 ^ - Float.ofNat res.exponent
  | Parsec.ParseResult.error it err  => Except.error s!"offset {it.i.repr}: {err}"

#eval parse "1.3" -- Except.ok 1.300000

Charles Hughes (Sep 21 2021 at 15:56):

Thanks Mac!


Last updated: Dec 20 2023 at 11:08 UTC