1 -----------------------------------------------------------------------------
2 -- $Id: Printf.lhs,v 1.3 2001/08/07 11:13:46 simonmar Exp $
4 -- (c) Simon Marlow 1997-2001
5 -----------------------------------------------------------------------------
7 > module Printf (showFloat, showFloat') where
17 > :: Bool -- Always print decimal point
18 > -> Bool -- Left adjustment
19 > -> Bool -- Always print sign
20 > -> Bool -- Leave blank before positive number
21 > -> Bool -- Use zero padding
22 > -> Maybe Int -- Field Width
23 > -> Maybe Int -- Precision
27 > bUFSIZE = 512 :: Int
29 > showFloat alt left sign blank zero width prec num =
30 > unsafePerformIO $ do
32 #if __GLASGOW_HASKELL__ < 500
34 > buf <- malloc bUFSIZE
35 > snprintf buf (fromIntegral bUFSIZE) (packString format) num
36 > let s = unpackCString buf
37 > length s `seq` -- urk! need to force the string before we
38 > -- free the buffer. A better solution would
39 > -- be to use foreign objects and finalisers,
40 > -- but that's just too heavyweight.
46 > allocaBytes bUFSIZE $ \buf -> do
47 > snprintf buf (fromIntegral bUFSIZE) (packString format) num
57 > if_bool blank " " ++
59 > if_maybe width show ++
60 > if_maybe prec (\s -> "." ++ show s) ++
63 > showFloat' :: Maybe Int -> Maybe Int -> Float -> String
64 > showFloat' = showFloat False False False False False
66 > if_bool False s = []
69 > if_maybe Nothing f = []
70 > if_maybe (Just s) f = f s
72 > type PackedString = ByteArray Int
74 #if __GLASGOW_HASKELL__ < 500
76 > foreign import unsafe snprintf :: Addr -> CSize -> PackedString -> Float -> IO ()
80 > foreign import unsafe snprintf :: CString -> CSize -> PackedString -> Float -> IO ()