Will
Will

Reputation: 4469

How to cast float to string with no decimal places

I'm using openpyxl to read values from a spreadsheet. These values are being read as floats, I am not entirely sure why.

import openpyxl as opx
wb = opx.load_workbook(SKU_WORKBOOK_PATH, use_iterators=True, data_only=True)
ws = wb.worksheets[0]
for row in ws.iter_rows():
  foo = str(int(row[1].internal_value))

This is throwing the error:

ValueError: invalid literal for int() with base 10: '6978279.0'

Normally, openpyxl reads in integer values as int, but this time it has read it in a float cast as a string. In the spreadsheet, the value of this cell is 6978279.

I am converting this to the string I want with foo = str(int(float(foo))) which results in '6978279' as intended. I could also do foo = foo[:-2], but this worries me that another cell, which may be read as an int or with more decimal places, would screw things up.

This feels like a terrible, messy way of mashing what I have into what I want. Is there a more pythonic way to do this? Am I reading the xlsx in a way that forces floats? How can I do this without triple casting?

Upvotes: 2

Views: 2260

Answers (2)

Compadre
Compadre

Reputation: 834

If you need int or float returned (may be for arithmetic operations), you can use a function like this:

def strip_num_or_float(value):
    try:
        value= int(value)
    except TypeError:
        value = value.normalize()
    return value

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

If you will never have decimals like 0.0 you can str.rstrip it will make 6978279.0 6978279 removing zeros from the end of any other decimals is not going to change its value 1.12300 will be 1.233:

In [20]: "1.234200".rstrip("0.")
Out[20]: '1.2342'

In [21]: "1.0".rstrip("0.")
Out[21]: '1'

If you could have 0.0 etc.. you could catch when the string is empty:

 In [22]: s = "0.0".rstrip("0.") or "0"

Upvotes: 1

Related Questions