2010-09-20 103 views
10

是否有庫函數將逗號與Haskell一起編號?Haskell:格式數字,包含逗號

我想要的功能,將工作是這樣的:

format 1000000 = "1,000,000" 
format 1045.31 = "1,045.31" 

,但我似乎無法找到任何數量的格式化這種類型在Haskell的功能。數字格式化功能在哪裏?

+4

++查詢圖書館而不是函數。 – 2010-09-20 15:47:22

+0

這可能與以下內容有關:http:// stackoverflow。com/questions/1388209/how-to-format-numbers-according-to-locale-in-haskell(如何根據區域設置數字格式) – sastanin 2010-09-20 16:02:18

+2

如果庫不存在,那麼你應該使用它作爲一個很好的藉口來寫你的第一個Haskell Cabal包。 – 2010-09-20 22:28:08

回答

8

也許你可以使用一些功能從Data.Split:

http://hackage.haskell.org/cgi-bin/hackage-scripts/package/split

我知道這ISN」噸相當你想要什麼,但你可以使用Data.List.intersperse

http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Data-List.html#v:intersperse

編輯:這你想要做什麼,但我知道你想要的庫函數,這可能是當你接近(請原諒我糟糕的編碼風格):

import Data.List.Split 
import Data.List 

format x = h++t 
    where 
     sp = break (== '.') $ show x 
     h = reverse (intercalate "," $ splitEvery 3 $ reverse $ fst sp) 
     t = snd sp 
+0

這實際上也是我的想法。 – 2010-09-20 15:59:44

+0

對於Floats,'show x'應該由'Numeric'包中的'showFFloat Nothing x'''替換。另外,'splitEvery'現在是'chunksOf'。 – VlatkoB 2014-03-21 09:14:05

0

(從票數:http://bluebones.net/2007/02/formatting-decimals-in-haskell/

格式小數在Haskell

甲FORMATT函數從333999333.33到Haskell中的「333,999,999.33」。對付負數並回合到2 dp(如果你願意,容易添加一個參數)。

實例:

*主要> formatDecimal 44

「44.00」

*主要> formatDecimal 94280943.4324

「94,280,943.43」

*主要> formatDecimal(-89438.329)

「-89,438.33」

import Data.Graph.Inductive.Query.Monad (mapFst) 
import List 
import Text.Printf 

formatDecimal d 
    | d < 0.0 = "-" ++ (formatPositiveDecimal (-d)) 
    | otherwise = formatPositiveDecimal d 
    where formatPositiveDecimal = uncurry (++) . mapFst addCommas . span (/= '.') . printf "%0.2f" 
      addCommas = reverse . concat . intersperse "," . unfoldr splitIntoBlocksOfThree . reverse 
      splitIntoBlocksOfThree l = case splitAt 3 l of ([], _) -> Nothing; p-> Just p 
0

我自己有這個問題。我非常實用的解決方案(使用Text as T)是這樣的:

T.replace (T.singleton '.') (T.singleton ',') $ 
T.pack $ 
showFixed False 42.0 

雖然對分隔符不起作用。這對我來說很好。

對我來說,除非有設置方法,否則語言環境沒有幫助。