How can I parse a semicolon instead of a decimal point?

I want to parse the values Floatfrom the file in which they are stored using a comma as a decimal separator. So, I need a function myParse :: String -> Floatsuch that, for example myParse "23,46" == 23.46.

I have some ideas on how to do this, but they all seem complicated, for example:

Is there an easier way, or do I really need to use a parsing library? In the second case, could you insert some sentences to start me? The limitation of monomorphism scares me, and I think there should be a way to do this without using language extensions.

+4
source share
2 answers

Replacing ,with ., and then calling is readquite simple; you just need to remember to use your own specialized function instead of the usual old one read:

readFloatWithComma :: String -> Float
readFloatWithComma = read . sanitize
  where
    sanitize = map (\c -> if c == ',' then '.' else c)

In GHCi:

λ> readFloatWithComma "23,46"
23.46

parsec, , , , , , . , - ( , GHC 7.10.1):

import Text.Parsec
import Text.Parsec.String         ( Parser )
import Control.Applicative hiding ( (<|>) )

infixr 5 <++>
(<++>) :: Applicative f => f [a] -> f [a] -> f [a]
a <++> b = (++) <$> a <*> b

infixr 5 <:>
(<:>) :: Applicative f => f a -> f [a] -> f [a]
a <:>  b = (:) <$> a <*> b

number :: Parser String
number = many1 digit

plus :: Parser String
plus = char '+' *> number

minus :: Parser String
minus = char '-' <:> number

integer :: Parser String
integer = plus <|> minus <|> number

float :: Parser Float
float = fmap rd $ integer <++> decimal <++> exponent
    where rd       = read :: String -> Float
          decimal  = option "" $ ('.' <$ char ',') <:> number
          exponent = option "" $ oneOf "eE" <:> integer

GHCi:

λ> parseTest float "23,46"
23.46
+6

float, , . , , , . : 1,2 = > 1,2; 1 234,56 = > 1234,56; 1,234,56 $= > 1234,56 , , - ...

function unformatNumber(value){
//remove symbols, spaces etc..
fvalue = value.replace(/[^0-9-,-.]/g, '');
//replace all non full stop characters with full stop
ffvalue=fvalue.replace(/[^0-9-.]/g,'.');
//remove all but last full stop
var last= ffvalue.lastIndexOf('.');
var butLast = ffvalue.substring(0,last).replace(/[^0-9]/g, '');
var res = butLast+ffvalue.substring(last);
//parse float
floatValue= parseFloat(res);
return floatValue;

}

-1

All Articles