在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 and setlocale个绑定,但有没有一个普通的漂亮的打印机尊重Lconv
?
答案 0 :(得分:1)
我会说,如果有问题的库丢失了,那么你可以自己写一个(显而易见的选项,不容易)或为所需的函数编写绑定。例如,sprintf
的限制绑定允许sprintf只加倍:
Double.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
double.h:
int toString(double a, char *buffer, int bufferLen);
double.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