Skip to content

How to convert bool/str/float to float? #3965

Answered by vitoyucepi
Moonbase59 asked this question in Q&A
Discussion options

You must be logged in to vote

If I were you, then I would convert everything to string, because every other type has a convenient to string conversion and then parse the string.

def something_to_float(value)
  value_string = string.case(string(value))
  possible_float =
    try
      float_of_string(value_string)
    catch _ do
      null()
    end
  possible_bool =
    try
      bool_of_string(value_string) ? 1. : 0.
    catch _ do
      null()
    end
  possible_float ?? possible_bool ?? 0.
end
Tests
a = true
b = false
c = "true"
d = "false"
e = "True"
f = "False"
g = "TRUE"
h = "FALSE"
i = 1.
j = -1.
k = "1."
l = "-1."
m = 1
n = -1
o = "1"
p = "-1"

def test(a)
  print(a)
  b = string.case(string(a))
  print(b)
  c =

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@Moonbase59
Comment options

@toots
Comment options

@Moonbase59
Comment options

@Moonbase59
Comment options

Answer selected by Moonbase59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants