Allow a comma and a point for money values

This commit is contained in:
Eike Kettner
2020-11-22 15:24:15 +01:00
parent bb19e02c66
commit c5ab663091
2 changed files with 26 additions and 9 deletions

View File

@ -131,14 +131,17 @@ initWith value =
Data.CustomFieldType.Numeric -> Data.CustomFieldType.Numeric ->
let let
( fm, _ ) = ( fm, _ ) =
updateFloatModel value.value string2Float updateFloatModel value.value string2Float identity
in in
NumberField fm NumberField fm
Data.CustomFieldType.Money -> Data.CustomFieldType.Money ->
let let
( fm, _ ) = ( fm, _ ) =
updateFloatModel value.value Data.Money.fromString updateFloatModel
value.value
Data.Money.fromString
Data.Money.normalizeInput
in in
MoneyField fm MoneyField fm
@ -175,14 +178,18 @@ type alias UpdateResult =
} }
updateFloatModel : String -> (String -> Result String Float) -> ( FloatModel, FieldResult ) updateFloatModel :
updateFloatModel msg parse = String
-> (String -> Result String Float)
-> (String -> String)
-> ( FloatModel, FieldResult )
updateFloatModel msg parse normalize =
case parse msg of case parse msg of
Ok n -> Ok n ->
( { input = msg ( { input = normalize msg
, result = Ok n , result = Ok n
} }
, Value msg , Value (normalize msg)
) )
Err err -> Err err ->
@ -216,7 +223,7 @@ update msg model =
( NumberMsg str, NumberField _ ) -> ( NumberMsg str, NumberField _ ) ->
let let
( fm, res ) = ( fm, res ) =
updateFloatModel str string2Float updateFloatModel str string2Float identity
model_ = model_ =
{ model | fieldModel = NumberField fm } { model | fieldModel = NumberField fm }
@ -229,6 +236,7 @@ update msg model =
updateFloatModel updateFloatModel
str str
Data.Money.fromString Data.Money.fromString
Data.Money.normalizeInput
model_ = model_ =
{ model | fieldModel = MoneyField fm } { model | fieldModel = MoneyField fm }

View File

@ -2,6 +2,7 @@ module Data.Money exposing
( Money ( Money
, format , format
, fromString , fromString
, normalizeInput
, roundMoney , roundMoney
) )
@ -13,8 +14,11 @@ type alias Money =
fromString : String -> Result String Money fromString : String -> Result String Money
fromString str = fromString str =
let let
input =
normalizeInput str
points = points =
String.indexes "." str String.indexes "." input
len = len =
String.length str String.length str
@ -22,7 +26,7 @@ fromString str =
case points of case points of
index :: [] -> index :: [] ->
if index == (len - 3) then if index == (len - 3) then
String.toFloat str String.toFloat input
|> Maybe.map Ok |> Maybe.map Ok
|> Maybe.withDefault (Err "Two digits required after the dot.") |> Maybe.withDefault (Err "Two digits required after the dot.")
@ -41,3 +45,8 @@ format money =
roundMoney : Float -> Float roundMoney : Float -> Float
roundMoney input = roundMoney input =
(round (input * 100) |> toFloat) / 100 (round (input * 100) |> toFloat) / 100
normalizeInput : String -> String
normalizeInput str =
String.replace "," "." str