user14608781
user14608781

Reputation:

Haskell; How to change int to a specific string?

In Haskell how am I able to convert the Int value 4496, into the String value 4.496m. As to represent 4.496 million?

Upvotes: 0

Views: 89

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 152682

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.

Upvotes: 1

karakfa
karakfa

Reputation: 67467

Not sure the scope of the question but here is one way...

Prelude> toMil x = show (x/1000)  ++ "m"
Prelude> toMil 4496
"4.496m"

Upvotes: 1

Related Questions