Casting to a "number" (both int and float)?

Ben Finney ben+python at benfinney.id.au
Fri Aug 28 01:44:06 EDT 2015


Victor Hooi <victorhooi at gmail.com> writes:

> Many of the fields are meant to be numerical, however, some fields are
> wrapped in a "floatApprox" dict, which messed with my parsing.

The examples you give of ‘floatApprox’ are not dicts, so I'm not sure
quite what that means.

> For example:
>
> {
>     "hostname": "example.com",
>     "version": "3.0.5",
>     "pid": {
>         "floatApprox": 18403
>     }
>     "network": {
>         "bytesIn": 123123,
>         "bytesOut": {
>             "floatApprox": 213123123
>         }
> }
>
> The floatApprox wrapping appears to happen sporadically in the input.

What do you mean by “wrapping”?

Can you show exactly what output values you would expect for these
example inputs?

> However, this relies on casting to int, which will only work for ints
> - for some fields, they may actually be floats, and I'd like to
> preserve that if possible.

(A terminology question: Note that “cast to int” isn't something that
happens in Python. You never “cast” an object as a different type, the
object is exactly what type it is and no other.

The example code you showed is not casting, but creating. Calling the
‘int’ type makes a new object of that type. Python doesn't have “cast”
as a concept.)

The question that needs to be answered is, how do you know what values
are “actually” floats?

In JSON there is no distinction at all, the only numeric type is
‘float’. What information is there in the input that can be used to know
which values should result in an ‘int’ instance, versus values that
should result in a ‘float’ instance?

-- 
 \                         “I'm a great lover, I'll bet.” —Emo Philips |
  `\                                                                   |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list