gpt4 book ai didi

localization - 如何根据 Haskell 中的语言环境格式化数字?

转载 作者:行者123 更新时间:2023-12-03 09:27:04 25 4
gpt4 key购买 nike

在 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 绑定(bind),但是是否有尊重 Lconv 的通用 pretty-print ?

最佳答案

我会说,如果缺少相关库,那么您可以自己编写一个(显而易见的选择,并不容易),或者为所需的函数编写一个绑定(bind)。例如,sprintf 的受限绑定(bind)这允许 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

关于localization - 如何根据 Haskell 中的语言环境格式化数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1388209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com