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. 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.
    – Blckknght
    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").

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.