This post is part of a series. To see all published posts in the series see the tag "elm calculator book".If you wish to support my work you can purchase the book on gumroad.
This project uses Elm version 0.19
- Part 1 - Introduction
- Part 2 - Project Setup
- Part 3 - Add CSS
- Part 4 - Basic Operations
- Part 5 - Adding Decimal Support
- Part 6 - Supporting Negative Numbers (this post)
- Part 7 - Add Dirty State
- Part 8 - Support Keypad Input
- Part 9 - Combination Key Input
- Part 10 - Testing
- Part 11 - Netlify Deployment
- browse: https://gitlab.com/pianomanfrazier/elm-calculator/-/tree/v0.6
- diff: https://gitlab.com/pianomanfrazier/elm-calculator/-/compare/v0.5...v0.6
- ellie: https://ellie-app.com/72p2Gt2gpkXa1
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
model
-- 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
else
{ 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.
Top comments (0)