From dcbb809ae1e4deda8b2c072146a662e10cebb98f Mon Sep 17 00:00:00 2001 From: Jonathan Lamothe Date: Thu, 28 Nov 2019 06:20:14 -0500 Subject: [PATCH] implemented showFloating --- src/Mtlstats/Format.hs | 8 ++++++-- test/FormatSpec.hs | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Mtlstats/Format.hs b/src/Mtlstats/Format.hs index e89fdf9..e7279fd 100644 --- a/src/Mtlstats/Format.hs +++ b/src/Mtlstats/Format.hs @@ -188,5 +188,9 @@ overlayLast str [l] = [overlay str l] overlayLast str (l:ls) = l : overlayLast str ls -- | Converts a non-integer into a string -showFloating :: Fractional n => n -> String -showFloating = undefined +showFloating :: RealFrac n => n -> String +showFloating n = let + i = round $ n * 100 + whole = i `div` 100 + fraction = i `mod` 100 + in show whole ++ "." ++ padNum 2 fraction diff --git a/test/FormatSpec.hs b/test/FormatSpec.hs index 9d17668..a7f7949 100644 --- a/test/FormatSpec.hs +++ b/test/FormatSpec.hs @@ -21,6 +21,7 @@ along with this program. If not, see . module FormatSpec (spec) where +import Data.Ratio ((%)) import Test.Hspec (Spec, context, describe, it, shouldBe) import Mtlstats.Format @@ -39,6 +40,7 @@ spec = describe "Mtlstats.Format" $ do tableWithSpec complexTableSpec overlayLastSpec + showFloatingSpec padNumSpec :: Spec padNumSpec = describe "padNum" $ do @@ -226,3 +228,11 @@ overlayLastSpec = describe "overlayLast" $ let [ ( "empty list", [], [] ) , ( "non-empty list", sample, edited ) ] + +showFloatingSpec :: Spec +showFloatingSpec = describe "showFloating" $ let + input = 3 % 2 :: Rational + expected = "1.50" + + in it ("should be " ++ expected) $ + showFloating input `shouldBe` expected