在Python中我可以使用locale.format
根据区域设置漂亮地打印数字:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
'en_US.UTF-8'
>>> locale.format("%.2f",1234567.89,grouping=True)
'1,234,567.89'
我怎样才能在 Haskell 中做同样的事情?我看到有localeconv 和 setlocale http://hackage.haskell.org/packages/archive/bindings-common/0.2.4/doc/html/Bindings-C.html#3绑定,但是有没有一个通用的漂亮打印机可以尊重Lconv
?
我想说,如果缺少相关的库,那么您可以自己编写一个(明显的选择,并不容易)或为所需的函数编写一个绑定。例如,限制绑定sprintf
它允许 sprintf 仅加倍:
双.hs:
{-# INCLUDE "double.h" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Double (cPrintf) where
import Foreign
import Foreign.C.Types
import System.IO.Unsafe
import qualified Data.ByteString as B
foreign import ccall "double.h toString"
c_toString :: CDouble -> (Ptr Word8) -> CInt -> IO CInt
buf = unsafePerformIO $ mallocBytes 64
cPrintf :: Double -> B.ByteString
cPrintf n = B.pack $ unsafePerformIO $ do
len <- c_toString (realToFrac n) buf 64
peekArray (fromIntegral len) buf
双.h:
int toString(double a, char *buffer, int bufferLen);
双.c:
#include <stdio.h>
#include "double.h"
int toString(double a, char *buffer, int bufferLen) {
return snprintf(buffer, bufferLen, "%f", a);
}
构建为:
gcc -c double.c
ghc --make Main.hs double.o
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)