Haskell - how to avoid scientific notation in decimal output

核能气质少年 提交于 2019-12-01 22:39:05

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.

Many thanks for all your comments, now I understand the problem I don't mind using workarounds. The code was to find the lengths of sections of music based on the time each section begins - in the form of 1.28 for 1 minute 28 seconds. Now the result is a list with the timings as strings but that is not a problem. For anyone who is interested, here is the function with the workaround:

subtractMinutes :: RealFrac a => [a] -> [[Char]]
subtractMinutes (x:xs) = take (length (xs)) (zz : subtractMinutes xs)
    where ya = (head(xs) - x) * 100
          ys = truncate (head(xs)) - truncate(x)
          yz = ya - (fromIntegral(ys) * 40)
          yx = round(yz)
          za = div yx 60
          zs = mod yx 60
          zz = show(za) ++ "." ++ zx
          zx = if zs < 10 then "0" ++ show(zs) else show(zs)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!