From 8966e765c83ef96bd69ca63cf18d3471c18377d8 Mon Sep 17 00:00:00 2001 From: Nikolay Orlyuk Date: Sun, 26 Mar 2017 07:08:37 +0200 Subject: [PATCH] prices: improve precision --- bin/hledger-prices.hs | 11 +++++++++-- tests/bin/prices.test | 5 +++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/bin/hledger-prices.hs b/bin/hledger-prices.hs index ab05f02c8..cbfa55798 100755 --- a/bin/hledger-prices.hs +++ b/bin/hledger-prices.hs @@ -13,7 +13,7 @@ import Data.Maybe import Data.String.Here import Data.Time import qualified Data.Text as T -import Control.Monad +import Control.Monad (when) import Hledger.Cli ------------------------------------------------------------------------------ @@ -30,6 +30,13 @@ Print all prices from the journal. showPrice :: MarketPrice -> String showPrice mp = unwords ["P", show $ mpdate mp, T.unpack . quoteCommoditySymbolIfNeeded $ mpcommodity mp, showAmountWithZeroCommodity $ mpamount mp] +divideAmount' :: Amount -> Quantity -> Amount +divideAmount' a d = a' where + a' = (a `divideAmount` d) { astyle = style' } + style' = (astyle a) { asprecision = precision' } + extPrecision = (1+) . floor . logBase 10 $ (realToFrac d :: Double) + precision' = extPrecision + asprecision (astyle a) + amountCost :: Day -> Amount -> Maybe MarketPrice amountCost d a = case aprice a of @@ -37,7 +44,7 @@ amountCost d a = UnitPrice pa -> Just MarketPrice { mpdate = d, mpcommodity = acommodity a, mpamount = pa } TotalPrice pa -> Just - MarketPrice { mpdate = d, mpcommodity = acommodity a, mpamount = pa `divideAmount` abs (aquantity a) } + MarketPrice { mpdate = d, mpcommodity = acommodity a, mpamount = pa `divideAmount'` abs (aquantity a) } postingCosts :: Posting -> [MarketPrice] postingCosts p = mapMaybe (amountCost date) . amounts $ pamount p where diff --git a/tests/bin/prices.test b/tests/bin/prices.test index 6479e7556..e312d0e85 100644 --- a/tests/bin/prices.test +++ b/tests/bin/prices.test @@ -34,8 +34,13 @@ P 2016/2/1 EUR $1.05 2016/1/2 spend expenses 20 EUR @ $1.07 assets:bank + +2016/1/3 spend + expenses 20 EUR @@ $21.45 + assets:bank >>> P 2016-01-02 EUR $1.07 +P 2016-01-03 EUR $1.0725 P 2016-01-01 EUR $1.06 P 2016-02-01 EUR $1.05 >>>2