如何在 Haskell 中填充整数的字符串表示形式? [英] How do I pad string representations of integers in Haskell?
本文介绍了如何在 Haskell 中填充整数的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种惯用的(可能是内置的)方法,在左侧用零填充整数的字符串表示形式.
I'l looking for an idiomatic (perhaps built-in) way of padding string representations of integers with zeros on the left.
在我的例子中,整数永远不会超过 99,所以
In my case the integers are never more than 99 so
fix r = if length r == 1 then '0':r else r
fix.show <$> [1..15]
有效.但我希望有更好的方法.
works. But I expect there is a better way.
如何在 Haskell 中填充整数的字符串表示形式?
How do I pad string representations of integers in Haskell?
推荐答案
printf
样式格式可通过 Text.Printf
模块获得:
printf
style formatting is availble via the Text.Printf
module:
import Text.Printf
fmt x = printf "%02d" x
或者特殊情况下0的格式:
Or to special case the formatting of 0:
fmt 0 = " "
fmt x = printf "%02d" x
这篇关于如何在 Haskell 中填充整数的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文