1

I'm very new to elm and i want to do a simple mileage counter app.

If i get "1.2" (POINT) form input - String.toFloat returns in the OK branch with 1.2 as a number.

But if i get "1,2" (COMMA) form input, then String.toFloat returns in the Err branch with "You can't have words, only numbers!"

This pretty much works like a real time validator. enter image description here

The code:

TypingInInput val ->
        case String.toFloat val of
            Ok success ->
                { model | inputValue = val, errorMessage = Nothing }

            Err err ->
                { model | inputValue = val, errorMessage = Just "You can't have words, or spaces, only numbers!" } 
   .

Question: So how can i force String.toFloat of "1,2" to give me 1.2 the number?

AIon
  • 12,521
  • 10
  • 47
  • 73

2 Answers2

4

Unfortunately the source for toFloat is hardcoded to only respect a dot as decimal separator. You can replace the comma with a dot in the string prior to passing it to toFloat as a workaround.

String.Extra.replace can be used for the simple string replacement.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • yes @Chad Gilbert. Thanks this looks way pretty! I replaced the case statement like this: `case String.toFloat (String.Extra.replace "," "." val) of` but i run into this errors : `I cannot find module String.Extra` or if i import only String exposing (..) i get: `Cannot find variable 'String.Extra.replace` , The qualifier `String.Extra` is not in scope`. I don't know how to solve this. How did you do it? – AIon Oct 08 '16 at 16:23
  • 1
    Run this from the command line: `elm package install elm-community/string-extra`. – Chad Gilbert Oct 08 '16 at 16:30
  • Thanks a lot @Chad Gilbert ! I forgot to do the install. Everything works fine now:) – AIon Oct 08 '16 at 16:36
  • 2
    I guess you could use `String.map` as well. – Tosh Oct 08 '16 at 20:10
1

The implementation of String.toFloat only supports a dot as a separator.

You should replace commas first before parsing the Float

Please see the example:

import Html exposing (text)
import String
import Regex


main =
  "1,2"
    |> Regex.replace Regex.All (Regex.regex ",") (\_ -> ".")
    |> String.toFloat
    |> toString
    |> text -- 1.2

In JavaScript parseFloat doesn't support comma separator either.

halfzebra
  • 6,771
  • 4
  • 32
  • 47