New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use BigDecimal compatible operation in NumberToRoundedConverter #42316
Use BigDecimal compatible operation in NumberToRoundedConverter #42316
Conversation
26f9496
to
78c10e2
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM @tom-lord wdyt?
It's a bit of a micro-optimisation but we can add a if rounded_number.nan?
"NaN"
elsif rounded_number.infinite?
"Inf"
elsif precision.zero?
"%i" % rounded_number
else
s = rounded_number.to_s("F")
s << "0" * precision
a, b = s.split(".", 2)
a << "."
a << b[0, precision]
end Could even go one step further and check for elsif rounded_number.frac.zero?
"%i.#{'0' * precision}" % rounded_number Unsure about the relative performance of |
78c10e2
to
8b28d54
Compare
My intuition said you were right, but I did some (simple) benchmark to test it out and it seems that the code with those allocations is faster (I've also added some changes to the code to make it a little bit faster). |
@federicoaldunate nice - I guess the parsing of the format string by |
8b28d54
to
bd6277d
Compare
@pixeltrix Did it, benchmark showed a little improvement in performance so I updated the code. |
@federicoaldunate thanks for bearing with my suggestions and checking them out 👍 |
Nice work @federicoaldunate!!! |
Hey, sorry for being slow replying here, you caught me on a bank holiday weekend with great weather 😉 I like the removal of the However, I also think this PR could have introduced another slight regression: consider
The new implementation of this method will format Weirdly, also note that Or alternatively, rather than hardcoding
|
@tom-lord Thanks for checking back and hope you had a good holiday :) I think I like your proposal, would you be willing to work on a PR? If not I can give it a shot 🙌 |
@pixeltrix Since you merged this, do you think it is worth backporting to 6.1? |
Summary
NumberToRoundedConverter
uses operations withBigDecimal
that will show inaccurate results due to the fact that the number is converted toFloat
to use that operation. Inaccuracies will arise whenFloat
cannot accurately store the number.Example
So any BigDecimal number that cannot be expressed as a float accurately will make this operation inaccurately.
This is an attempt to fix #42302
Other Information
Now that
rounded_number == rounded_number.to_i
condition is not needed I changed the if...else to return'Nan'
whenrounded_number.nan?
and'Inf'
whenrounded_number.infinite?
instead of"%00.#{precision}f" % rounded_number
that returns the same string for those cases