From 18f6424397bf3bbfd6a7793b40ec81de3a2b9ff5 Mon Sep 17 00:00:00 2001 From: Guntis Smaukstelis Date: Mon, 22 May 2023 22:24:12 +0300 Subject: [PATCH] Implicit for rounding double values to first decimal --- src/main/scala/parse/Aggregate.scala | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/scala/parse/Aggregate.scala b/src/main/scala/parse/Aggregate.scala index 6e31d60..497782f 100644 --- a/src/main/scala/parse/Aggregate.scala +++ b/src/main/scala/parse/Aggregate.scala @@ -101,6 +101,10 @@ object Aggregate { case _ => List.empty } + implicit class RoundDecimal(val d: Double) extends AnyVal { + def roundDecimal: Double = BigDecimal(d).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble + } + def aggregateDoubleValues( AggKey: AggregateKey, values: List[Option[Double]], @@ -108,10 +112,10 @@ object Aggregate { ): Option[AggregateValue] = { val flatValues = values.flatten AggKey match { - case AggregateKey.Min => flatValues.minimumOption.map(DoubleValue) - case AggregateKey.Max => flatValues.maximumOption.map(DoubleValue) - case AggregateKey.Avg => flatValues.reduceOption(_ + _).map(sum => DoubleValue(sum / flatValues.length)) - case AggregateKey.Sum => flatValues.sum.some.map(DoubleValue) + case AggregateKey.Min => flatValues.minimumOption.map(value => DoubleValue(value.roundDecimal)) + case AggregateKey.Max => flatValues.maximumOption.map(value => DoubleValue(value.roundDecimal)) + case AggregateKey.Avg => flatValues.reduceOption(_ + _).map(sum => DoubleValue((sum / flatValues.length).roundDecimal)) + case AggregateKey.Sum => flatValues.sum.some.map(value => DoubleValue(value.roundDecimal)) case AggregateKey.List => TimeDoubleList(timestamps.zip(values).sorted).some case AggregateKey.Distinct => None }