In Haskell how am I able to convert the Int value 4496, into the String value 4.496m. As to represent 4.496 million?
-
3What did you try? What is not working?willeM_ Van Onsem– willeM_ Van Onsem2021-03-22 20:08:18 +00:00Commented Mar 22, 2021 at 20:08
-
Welcome to stackoverflow. Take a look at how to ask questions stackoverflow.com/help/how-to-askuser1198582– user11985822021-03-23 01:40:32 +00:00Commented Mar 23, 2021 at 1:40
2 Answers
Not sure the scope of the question but here is one way...
Prelude> toMil x = show (x/1000) ++ "m"
Prelude> toMil 4496
"4.496m"
The alternative answer, using x/1000, has some fun behaviors that may or may not be what you want. For example:
> 0/1000
0.0 -- not 0.000
> 1/1000
1.0e-3 -- scientific notation
> (2^53)/1000 == (2^53+1)/1000
True -- imprecise
There may be examples where rounding will bite you as well, causing some output like A.BCD9999999 or something, though I'm not sure how to construct one quickly. An alternative that has a predictable format is to use the built-in Fixed family of types for fixed point arithmetic; the Milli type in particular being relevant. The above examples print like this:
> 0/1000 :: Milli
0.000
> 1/1000 :: Milli
0.001
> (2^53)/1000 == ((2^53+1) / 1000 :: Milli)
False
Here's a complete code snippet showing how to use it:
import Data.Fixed
toMil :: Int -> String
toMil x = show (MkFixed (toInteger x) :: Milli) ++ "m"
In fact, you might just want to start from having a Milli lying around in the first place rather than an Int -- it will give you all sorts of nice things, like multiplication behaving in the way you expect:
> 1000 * 1000 :: Int
1000000
> let MkFixed n = MkFixed 1000 * (MkFixed 1000 :: Milli) in n
1000
That is, 1000 milli-things is 1 thing, and 1*1 thing = 1 thing = 1000 milli-things, not 1000000 milli-things.