Skip to content

Commit fa30c8f

Browse files
committed
Fix decimal and double #round method to round towards positive for negative numbers, as called for in XPath function.
1 parent 085cc59 commit fa30c8f

3 files changed

Lines changed: 20 additions & 10 deletions

File tree

lib/rdf/model/literal/decimal.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,15 @@ def abs
6363
##
6464
# Returns the number with no fractional part that is closest to the argument. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if arg is not a numeric value.
6565
#
66-
# @return [RDF::Literal::Integer]
66+
# @return [RDF::Literal::Decimal]
6767
def round
68-
RDF::Literal::Integer.new(to_d.round)
68+
rounded = to_d.round(half: (to_d < 0 ? :down : :up))
69+
if rounded == -0.0
70+
# to avoid -0.0
71+
self.class.new(0.0)
72+
else
73+
self.class.new(rounded)
74+
end
6975
end
7076

7177
##

lib/rdf/model/literal/double.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,11 +181,11 @@ def abs
181181
end
182182

183183
##
184-
# Returns the integer with no fractional part that is closest to the argument. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if arg is not a numeric value.
184+
# Returns the number with no fractional part that is closest to the argument. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if arg is not a numeric value.
185185
#
186-
# @return [RDF::Literal::Integer]
186+
# @return [RDF::Literal::Double]
187187
def round
188-
RDF::Literal::Integer.new(to_f.round)
188+
self.class.new(to_d.round(half: (to_d < 0 ? :down : :up)))
189189
end
190190

191191
##

spec/model_literal_spec.rb

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1044,12 +1044,16 @@ def self.literals(*selector)
10441044
0 => 0,
10451045
BigDecimal("1.1") => BigDecimal("1"),
10461046
BigDecimal("-1.1") => BigDecimal("-1"),
1047+
BigDecimal("0.5") => BigDecimal("1"),
1048+
BigDecimal("-0.5") => BigDecimal("0"),
10471049
BigDecimal("1.5") => BigDecimal("2"),
1048-
BigDecimal("-1.5") => BigDecimal("-2"),
1049-
+0.0 => 0,
1050-
-0.0 => 0,
1051-
1.5 => 2,
1052-
-1.5 => -2,
1050+
BigDecimal("-1.5") => BigDecimal("-1"),
1051+
+0.0e0 => 0.0e0,
1052+
-0.0e0 => 0e0,
1053+
0.5e0 => 1e0,
1054+
-0.5e0 => -0e0,
1055+
1.5e0 => 2e0,
1056+
-1.5e0 => -1e0,
10531057
1.2e0 => 1.0e0,
10541058
-1.2e0 => -1.0e0
10551059
}.each do |value, result|

0 commit comments

Comments
 (0)