Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a decimal string from a Double instead of scientific notation in Haskell?

I need to divide a list of numbers by 100 to be printed, for example:

map (/100) [29, 3, 12]

produces:

[0.29,3.0e-2,0.12]

however I need:

[0.29,0.03,0.12]

How do I do this in Haskell? Any ideas really appreciated.

like image 272
Ian Stewart Avatar asked May 03 '16 14:05

Ian Stewart


People also ask

What is Scipen?

Scipen: A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider.

What is Sciscientific notation?

Scientific notation is a way of writing very large or very small numbers. A number is written in scientific notation when a number between 1 and 10 is multiplied by a power of 10. For example, 650,000,000 can be written in scientific notation as 6.5 ✕ 10^8.


2 Answers

0.03 and 3.0e-2 are the same number. Internally, GHC uses showFloat to print it, which will result in the scientific notation whenever the absolute value is outside the range 0.1 and 9,999,999.

Therfore, you have to print the values yourself, for example with printf from Text.Printf or showFFloat from Numeric:

import Numeric

showFullPrecision :: Double -> String
showFullPrecision x = showFFloat Nothing x ""

main = putStrLn (showFullPrecision 0.03)

Depending on your desired output, you need to write some more functions.

like image 117
Zeta Avatar answered Nov 09 '22 17:11

Zeta


What works for me is: cabal install numbers and then in GHCi

λ: import Data.Number.CReal
λ: map (/(100 :: CReal)) [29,3,12]
[0.29,0.03,0.12]
like image 43
Golden Thumb Avatar answered Nov 09 '22 17:11

Golden Thumb