Haskell printf转换为字符串 [英] Haskell printf to string

查看:129
本文介绍了Haskell printf转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell中是否有sprintf等效项?

Is there a sprintf equivalent in Haskell?

我需要将双精度值转换为字符串并将其格式化为字符串.

I need to convert and format double values into strings.

还有没有使用 printf 类功能的另一种方法吗?

Is there another way without using printf kind of functions?

主要问题是避免:

Prelude> putStrLn myDoubleVal
1.7944444444444447e-2

相反,我想要这个:

Prelude> putStrLn . sprintf "%.2f" $ myDoubleVal
1.79

推荐答案

是的,它位于

Yes, it's in the Text.Printf module, and it's just called printf.

> import Text.Printf
> let x = 1.14907259
> putStrLn . printf "%.2f" $ x
1.15

请注意,printf的返回类型已重载,因此它可以返回String(如上例所示),但也可以返回执行打印的I/O操作,因此您实际上不需要调用putStrLn:

Note that the return type of printf is overloaded, so that it's capable of returning a String (as in the example above) but it's also capable of returning an I/O action that does the printing, so you don't actually need the call to putStrLn:

> printf "%.2f\n" x
1.15

这篇关于Haskell printf转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆