Skip to content
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

Fix strformat neg zero #7954

Merged
merged 5 commits into from
Jun 5, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/pure/strformat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -527,8 +527,13 @@ proc format*(value: SomeFloat; specifier: string; res: var string) =
var sign = false
if value >= 0.0:
if spec.sign != '-':
f = spec.sign & f
sign = true
if value == 0.0:
if 1.0 / value == Inf:
# only add the sign if value != negZero
f = spec.sign & f
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you use insert instead, to modify 'f' in place? It would be nice to reduce the number of temporary string allocations made in this procedure.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are other places where we could use insert instead of string concatenation, but i limit the change strictly to the area i want to fix (no + in front of negative zero).

Personally i don't like inplace mutations, therefore I will not produce PR's to change other places in strformat to use inplace mutations.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't matter if you like them or not, they are faster and this is a "standard library" where everybody benefits from faster code.

else:
f = spec.sign & f
else:
sign = true

Expand Down
8 changes: 8 additions & 0 deletions tests/stdlib/tstrformat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,11 @@ doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative fl
doAssert fmt"{-1.5:08}" == "-00001.5" # works
doAssert fmt"{1.5:+08}" == "+00001.5" # works
doAssert fmt"{1.5: 08}" == " 00001.5" # works

# only add explicitly requested sign if value != -0.0 (neg zero)
doAssert fmt"{-0.0:g}" == "-0"
doassert fmt"{-0.0:+g}" == "-0"
doassert fmt"{-0.0: g}" == "-0"
doAssert fmt"{0.0:g}" == "0"
doAssert fmt"{0.0:+g}" == "+0"
doAssert fmt"{0.0: g}" == " 0"