lib: Do not round Decimal before applying JSON representation if

existing representation is small enough.

Previously the JSON representation of Decimal was rounded to 10 points
of precision before serialising. This sometimes results in an
unnecessary increase of precision.
This commit is contained in:
Stephen Morgan 2021-03-26 15:22:47 +11:00 committed by Simon Michael
parent 55772cbd9b
commit a529207ae7
2 changed files with 16 additions and 16 deletions

View File

@ -41,8 +41,8 @@ import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePrettyToTextBuilder)
--import Data.Aeson.TH
import qualified Data.ByteString.Lazy as BL
import Data.Decimal
import Data.Maybe
import Data.Decimal (DecimalRaw(..), roundTo)
import Data.Maybe (fromMaybe)
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Text.Lazy.Builder as TB
@ -80,13 +80,13 @@ instance ToJSON GenericSourcePos
-- and that the overall number of significant digits in the floating point
-- remains manageable in practice. (I'm not sure how to limit the number
-- of significant digits in a Decimal right now.)
instance ToJSON Decimal where
instance (Integral a, ToJSON a) => ToJSON (DecimalRaw a) where
toJSON d = object
["decimalPlaces" .= toJSON decimalPlaces
,"decimalMantissa" .= toJSON decimalMantissa
,"floatingPoint" .= toJSON (fromRational $ toRational d' :: Double)
]
where d'@Decimal{..} = roundTo 10 d
[ "decimalPlaces" .= toJSON (decimalPlaces d')
, "decimalMantissa" .= toJSON (decimalMantissa d')
, "floatingPoint" .= toJSON (realToFrac d' :: Double)
]
where d' = if decimalPlaces d <= 10 then d else roundTo 10 d
instance ToJSON Amount
instance ToJSON AmountStyle

View File

@ -18,8 +18,8 @@ $ hledger -f- reg --output-format=json
"acommodity": "AAA",
"aquantity": {
"floatingPoint": 1,
"decimalPlaces": 10,
"decimalMantissa": 10000000000
"decimalPlaces": 1,
"decimalMantissa": 10
},
"aismultiplier": false,
"astyle": {
@ -46,8 +46,8 @@ $ hledger -f- reg --output-format=json
"acommodity": "AAA",
"aquantity": {
"floatingPoint": 1,
"decimalPlaces": 10,
"decimalMantissa": 10000000000
"decimalPlaces": 1,
"decimalMantissa": 10
},
"aismultiplier": false,
"astyle": {
@ -76,8 +76,8 @@ $ hledger -f- bal --output-format=json
"acommodity": "AAA",
"aquantity": {
"floatingPoint": 1,
"decimalPlaces": 10,
"decimalMantissa": 10000000000
"decimalPlaces": 1,
"decimalMantissa": 10
},
"aismultiplier": false,
"astyle": {
@ -97,8 +97,8 @@ $ hledger -f- bal --output-format=json
"acommodity": "AAA",
"aquantity": {
"floatingPoint": 1,
"decimalPlaces": 10,
"decimalMantissa": 10000000000
"decimalPlaces": 1,
"decimalMantissa": 10
},
"aismultiplier": false,
"astyle": {