Haskell 是否有某种数字转换为科学格式?

Does Haskell have some sort of number conversion to scientific format?

在 JS 中,我们有 Number.toExponential() 将数字转换为科学记数法(即:对于 1000 -> "1e3")。

我查看了 hoggle,但我似乎找不到它。

注意:toExponential 变化 num -> string

您可以使用 printf :: PrintfType r => String -> r 并使用 %e%E 说明符:

Prelude> import Text.Printf
Prelude Text.Printf> <strong>printf "%e"</strong> 14.25 :: String
"1.425e1"
Prelude Text.Printf> <strong>printf "%E"</strong> 14.25 :: String
"1.425E1"

这里%e指定科学记数法小写e%E大写Eprintf 的输出类型可以是 StringIO ()。如果使用 String 类型,我们会得到一个带有格式化类型的 String,对于 IO (),它会将类型打印到标准输出。


the showEFloat :: RealFloat a => Maybe Int -> a -> String -> String to prepend a string with the exponential representation of a RealFloat 号码类型。


您也可以使用 Scientific 数字,然后使用 formatScientific :: FPFormat -> Maybe Int -> Scientific -> String

如果您这样安装 scientific package,我们可以通过以下方式实现:

Prelude> import Data.Scientific
Prelude Data.Scientific> <strong>formatScientific Exponent Nothing</strong> 1000
"1.0e3"

这意味着 1000 类型应该是 Scientific 而不是 `