Skip to content

Commit 55dde8a

Browse files
committed
Invert ifdef logic, use numeric code rather than string-as-list manipulation for no-double-conversion 'shortest' formatter
1 parent faa449a commit 55dde8a

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

src/Data/Text/Format.hs

+15-16
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,10 @@ module Data.Text.Format
2424
, shortest
2525
) where
2626

27-
#ifndef MIN_VERSION_double_conversion
28-
import Data.List (dropWhileEnd, isSuffixOf)
29-
import Numeric (showFFloat)
30-
#else
27+
#ifdef MIN_VERSION_double_conversion
3128
import Data.Double.Conversion.Text (toFixed, toShortest)
29+
#else
30+
import Numeric (showFFloat, showInt)
3231
#endif
3332
import qualified Formatting.Buildable as B
3433
import Data.Text.Format.Types (Hex(..))
@@ -54,31 +53,31 @@ fixed :: (Real a) =>
5453
Int
5554
-- ^ Number of digits of precision after the decimal.
5655
-> a -> Builder
57-
#ifndef MIN_VERSION_double_conversion
56+
#ifdef MIN_VERSION_double_conversion
57+
fixed decs = fromText . toFixed decs . realToFrac
58+
#else
5859
fixed decs = fromString . toFixed . realToFrac
5960
where
6061
toFixed :: Double -> String
6162
toFixed dbl = showFFloat (Just decs) dbl ""
62-
#else
63-
fixed decs = fromText . toFixed decs . realToFrac
6463
#endif
6564
{-# NOINLINE[0] fixed #-}
6665

6766
-- | Render a floating point number using the smallest number of
6867
-- digits that correctly represent it.
6968
shortest :: Real a => a -> Builder
70-
#ifndef MIN_VERSION_double_conversion
69+
#ifdef MIN_VERSION_double_conversion
70+
shortest = fromText . toShortest . realToFrac
71+
#else
7172
shortest = fromString . toShortest . realToFrac
7273
where
7374
toShortest :: Double -> String
74-
toShortest dbl = do
75-
let shownFullPrec = showFFloat Nothing dbl ""
76-
strip = dropWhileEnd (== '0') shownFullPrec
77-
if "." `isSuffixOf` strip
78-
then take (length strip - 1) strip
79-
else strip
80-
#else
81-
shortest = fromText . toShortest . realToFrac
75+
toShortest dbl =
76+
-- `showFFloat (Just 0) "" 1.0` gives "1.", but we want "1"
77+
let intPart = (floor dbl :: Int) in
78+
if dbl == (fromIntegral intPart)
79+
then showInt intPart ""
80+
else showFFloat Nothing dbl ""
8281
#endif
8382
{-# INLINE shortest #-}
8483

0 commit comments

Comments
 (0)