Skip to content

Commit f3ba580

Browse files
Format small floats without scientific notation in XPath string() (#395)
The XPath `string()` function formats a number that is not an integer with Ruby's `Float#to_s`, which switches to scientific notation for small values. XPath 1.0 has no exponent syntax for numbers (section 4.2 describes the number-to-string conversion in decimal form), and `number()` cannot read such a string back: ```ruby doc = REXML::Document.new("<a/>") REXML::XPath.first(doc, "string(0.00001)") # => "1.0e-05" REXML::XPath.first(doc, "string(0.0000123)") # => "1.23e-05" REXML::XPath.first(doc, "string(1 div 10000000000)") # => "1.0e-10" REXML::XPath.first(doc, "number(string(0.00001))") # => NaN ``` After this change a value whose `to_s` has a negative exponent is written in decimal form (`"0.00001"`, `"0.0000123"`, `"0.0000000001"`, and `"-0.00001"` for a negative one), so `number(string(x))` gives `x` back. Integers, and floats whose `to_s` has no exponent, are unchanged.
1 parent 4d3849b commit f3ba580

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎lib/rexml/functions.rb‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,15 @@ def string( object=@context[:node] )
161161
if object == integer
162162
"%d" % integer
163163
else
164-
object.to_s
164+
str = object.to_s
165+
if str.include?("e-")
166+
sign = str.start_with?("-") ? "-" : ""
167+
mantissa, exp = str.delete_prefix("-").split("e-", 2)
168+
digits = mantissa.delete(".").sub(/0+\z/, "")
169+
"#{sign}0.#{'0' * (exp.to_i - 1)}#{digits}"
170+
else
171+
str
172+
end
165173
end
166174
end
167175
else

‎test/functions/test_base.rb‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,15 @@ def test_string_infinity
254254
])
255255
end
256256

257+
def test_string_small_float
258+
doc = REXML::Document.new("<a/>")
259+
assert_equal("0.00001", REXML::XPath.first(doc, "string(0.00001)"))
260+
assert_equal("-0.00001", REXML::XPath.first(doc, "string(-0.00001)"))
261+
assert_equal("0.0000123", REXML::XPath.first(doc, "string(0.0000123)"))
262+
assert_equal("0.0000000001", REXML::XPath.first(doc, "string(1 div 10000000000)"))
263+
assert_equal(0.00001, REXML::XPath.first(doc, "number(string(0.00001))"))
264+
end
265+
257266
# Submitted by Kou
258267
def test_lang
259268
d = Document.new(<<-XML)

0 commit comments

Comments
 (0)