Elm Calculator Part 6 - Supporting Negative Numbers

April 17, 2020 ยท 2 minute read

This post is part of a series. If you wish to support my work you can purchase the PDF book on gumroad.

This project uses Elm version 0.19

Users need to be able to input negative numbers. Since negatives are different than the subtract operation we need to handle this separately.

Many RPN calculators I have seen have a toggle sign button.

section : Html Msg
section =
    div [ class "section" ]
        [ ...
        , cell (onClick SetSign) Single White "+/-"
        , cell (onClick Enter) Single Yellow "Enter"

And then let's add the message type and update the model.

type Msg
    = ...
    | SetSign

We need to do some string checking to make this work.

update : Msg -> Model -> Model
update msg model =
    case msg of
        SetSign ->
            -- don't allow the user to make a negative zero
            if model.currentNum == "0" then

            -- drop the negative sign from the string
            else if String.startsWith "-" model.currentNum then
                { model | currentNum = String.dropLeft 1 model.currentNum }

            -- add the negative sign
                { model | currentNum = "-" ++ model.currentNum }

And that's it. We now have a working calculator.

The next few chapters will be adding some nice extra features.