如何在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屋!
查看全文