如何根据 Haskell 中的区域设置格式化数字?

发布于 2024-08-03 23:38:25 字数 514 浏览 7 评论 0原文

在 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'

How can I do the same in Haskell?我看到有 localeconv 和 setlocale 绑定,但是是否有一个通用的漂亮打印机尊重 Lconv

In Python I can use locale.format to pretty-print numbers according to locale setting:

>>> 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'

How can I do the same in Haskell? I see that there are localeconv and setlocale bindings, but is there a generic pretty printer which respects Lconv?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔少女心 2024-08-10 23:38:25

我想说,如果缺少相关库,那么您可以自己编写一个(明显的选择,并不容易)或为所需的函数编写一个绑定。例如,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

I would say that if the library in question is missing then you could either write yourself one (obvious option, not easy) or write a binding for the needed function. For example, restricted binding for sprintf which allows to sprintf only doubles:

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);
}

Build as:

gcc -c double.c
ghc --make Main.hs double.o
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文