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
you could use the float() function
I think float() function only works for Int and IntLiterals. It doesn't works for string and StringLiterals.
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](https://cdn.answeroverflow.com/1186978426243002398/SCR-20231220-jpbh.png)
Check out the
test_float_utils.mojo
unit in the repo root to get started with it!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.
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 😉
Sure, I will let you know once implemented properly. Currently its working but not very well organised 🥲
Here is the really cheesy way to do it:
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 😉
There is also the option of using
external_call
and the strtof
C function, like so
Although of course the obligatory "current FFI is not stable and expect it to change" disclosure must be included