guess_types turns negative percentages into positive
Created originally on Bitbucket by mdemenok (Mike Demenok)
The regex used to parse percentages out of strings currently drops the minus sign, turning negative numbers into positive.
Reproducible case:
#!python
import openpyxl, re
wb = openpyxl.Workbook(guess_types=True)
ws = wb.active
ws.cell(row=1, column=1, value="Broken value")
cell = ws.cell(row=1, column=2, value="-20%")
print("This should be negative, but isn't: {}".format(cell.value))
openpyxl.cell.cell.PERCENT_REGEX = re.compile(r'^(?P<number>-?[0-9]*\.?[0-9]*\s?)\%$')
ws.cell(row=2, column=1, value="Correct value")
cell = ws.cell(row=2, column=2, value="-20%")
print("This should be negative, and is: {}".format(cell.value))
wb.save("negative_percentages.xlsx")
It's a simple fix by moving the - sign into the capture group, i.e. change from:
#!python
PERCENT_REGEX = re.compile(r'^\-?(?P<number>[0-9]*\.?[0-9]*\s?)\%$')
to
#!python
PERCENT_REGEX = re.compile(r'^(?P<number>-?[0-9]*\.?[0-9]*\s?)\%$')
Please note that same problem exists in NUMBER_REGEX, but the capture group result is never actually used. Consider updating it as well in case this changes in the future.
Attachments: openpyxl_819_repr.py