0

Today i noticed following issue on IronPython2.7:

When formatting a format_string like so, i get a "negativ zero". I get the same result if i use Python2.7 or Python3.4 instead of IronPython.

>>> "%.2f" % -0.004
'-0.00'

Then i realized, that i can get rid of the negativ zero by passing two arguments to the format string like so:

>>> "%s%.2f" % ('x', -0.004)
'x0.00'

'x' is a random character. So, i format another string before the float value and the minus disappears. That does not work with Python2.7 and Python3.4 though, where i get:

>>> "%s%.2f" % ('x', -0.004)
'x-0.00'

Does anybody know what's going on here?

What is the purpose of the formatted "negativ zero" at all?

2
  • Sounds like a bug in IronPython. It's supposed to follow the CPython reference implementation wherever feasible. Commented Jan 10, 2017 at 8:30
  • I'm not sure if you're aware, but negative zero is a perfectly valid float value: -0.0. It's distinct from (but equal to) positive zero. No idea why IronPython makes the minus sign disappear with there's another value in the format string. Commented Jan 10, 2017 at 9:06

1 Answer 1

0

(edited to take @MarkDikinson comment into account)

You can format the number first, then doing the printf-like formatting:

"%.2f" % (round(-0.004, 2)+0)

The +0 is there to remove the negative zero sign.

round can also take a ndigits argument, to specify how many digits you need for the rounding of the number itself (not talking about display, which is handled by "%.2f").

Sign up to request clarification or add additional context in comments.

4 Comments

Why use NumPy's around instead of Python's built-in round function? (And you probably want to round to 2 decimal places ...)
@MarkDickinson you're right ! I use numpy all the time at work but there is a standard round too ;)
@mguijarr installing numpy for ironpython could be problematic
@Odomontois indeed, that's why I simply removed numpy from my answer, I just originally forgot about standard round function ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.