How to convert string to float value?

Is there any way to convert string like "3.14" to float value? I can see atol is there for converting string to int value but couldn't find anything for float values.
10 Replies
Phantom
Phantom9mo ago
you could use the float() function
Vijay Yadav
Vijay Yadav9mo ago
I think float() function only works for Int and IntLiterals. It doesn't works for string and StringLiterals.
carlcaulkett
carlcaulkett9mo ago
Hi Vijay! Have a look at https://github.com/carlca/ca_mojo.git, in particular the float_utils or fu module. From the README.md...
No description
carlcaulkett
carlcaulkett9mo ago
Check out the test_float_utils.mojo unit in the repo root to get started with it!
Vijay Yadav
Vijay Yadav9mo ago
Thanks carl! Its really helpful. You may include a case where float string is something like this "1.314E-3" in your library. I had implemented this case already but its seems slow that's why I was wondering if mojo have in-built function.
carlcaulkett
carlcaulkett9mo ago
Ooh! I’d forgotten about that format. Good call! I’ll let you know when I do that… Or if you do it, you can let me know 😉
Vijay Yadav
Vijay Yadav9mo ago
Sure, I will let you know once implemented properly. Currently its working but not very well organised 🥲
Arthur Evans
Arthur Evans9mo ago
Here is the really cheesy way to do it:
let fstr = "1.345E-3"
let float = Python.evaluate("float(" + fstr + ")").to_float64()
let fstr = "1.345E-3"
let float = Python.evaluate("float(" + fstr + ")").to_float64()
carlcaulkett
carlcaulkett9mo ago
I'm in the fortunate position of not having any looming deadlines for my code noodling, so I can afford to maintain a pure-mojo approach 😉
Stole
Stole9mo ago
There is also the option of using external_call and the strtof C function, like so
let s: String = "1.48e2"
let f: Float32 = external_call["strtof", Float32, DTypePointer[DType.int8], Pointer[Int8]](s._as_ptr(), Pointer[Int8].get_null())
s._strref_keepalive()
let s: String = "1.48e2"
let f: Float32 = external_call["strtof", Float32, DTypePointer[DType.int8], Pointer[Int8]](s._as_ptr(), Pointer[Int8].get_null())
s._strref_keepalive()
Although of course the obligatory "current FFI is not stable and expect it to change" disclosure must be included
Want results from more Discord servers?
Add your server