coin-1.0: src/Coin/Utils/ValueParser.hs
{-
* Programmer: Piotr Borek
* E-mail: piotrborek@op.pl
* Copyright 2016 Piotr Borek
*
* Distributed under the terms of the GPL (GNU Public License)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Coin.Utils.ValueParser (
parseValue,
valueShow
) where
charToInt :: Char -> Maybe Int
charToInt '0' = Just 0
charToInt '1' = Just 1
charToInt '2' = Just 2
charToInt '3' = Just 3
charToInt '4' = Just 4
charToInt '5' = Just 5
charToInt '6' = Just 6
charToInt '7' = Just 7
charToInt '8' = Just 8
charToInt '9' = Just 9
charToInt _ = Nothing
parseValue :: String -> Maybe Int
parseValue [] = Nothing
parseValue text = parseValueA (reverse text) 0 100
parseValueA :: String -> Int -> Int -> Maybe Int
parseValueA [] acc _ = return acc
parseValueA (x:xs) acc mult =
if or [x == ',', x == '.']
then
if mult == 10000
then parseValueB xs (acc `div` 100) (mult `div` 100)
else Nothing
else do
digit <- charToInt x
parseValueA xs (acc + mult * digit) (mult * 10)
parseValueB :: String -> Int -> Int -> Maybe Int
parseValueB [] acc _ = return acc
parseValueB (x:xs) acc mult = do
digit <- charToInt x
parseValueB xs (acc + mult * digit) (mult * 10)
valueShow :: (Num n, Show n) => n -> String
valueShow val = let (a, b) = splitAt 2 $ reverse val'
in reverse b ++ "." ++ reverse a
where
val' = let text = show val
in case length text of
0 -> "000"
1 -> "00" ++ text
2 -> "0" ++ text
_ -> text