Cell Value of type 'n' incorrect precision

54 views
Skip to first unread message

Alfredo Yanez

unread,
Jul 7, 2023, 7:46:31 PM7/7/23
to openpyxl-users
I have a question about reading cell values while in data_only is True and keep_vba is False

I have the following code:
```
wb = openpyxl.load_workbook(file, keep_vba=True, data_only=True)
sheet = workbook["sheet_name"]
my_value = sheet["E22"].value
# My Value is 12659.539200000001
# but in the excel file it shows up as 12660.00
```
if I do sheet["E22"].data_type I get 'n'
if I do sheet["E22"].number_format I get `#,##0`

Is there a way to get the true value of the cell ?

Thanks !

Cuatro Jones

unread,
Jul 7, 2023, 11:08:55 PM7/7/23
to openpyx...@googlegroups.com
You could try casting it:
my_value = float(sheet["E22"].value)


--
You received this message because you are subscribed to the Google Groups "openpyxl-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to openpyxl-user...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/openpyxl-users/b338ace6-c658-4144-afe2-fecfdf5c0386n%40googlegroups.com.

Charlie Clark

unread,
Jul 10, 2023, 6:34:29 AM7/10/23
to openpyxl-users

This is just a side-effect of floating point mathematics and unavoidable. You have two options: use the decimal type or round the number to the precision you want.

Charlie

--
Charlie Clark
Managing Director
Clark Consulting & Research
German Office
Sengelsweg 34
Düsseldorf
D- 40489
Tel: +49-203-3925-0390
Mobile: +49-178-782-6226

Reply all
Reply to author
Forward
0 new messages