user5740843 user5740843 - 3 months ago 9
JSON Question

Cast string with decimal to int before putting it in JSON over Python

I'm trying to change a value, which is parsed through CGI over GET to Python before I want to send all the values over MQTT with JSON.

The value is as follows:

exposure = "0.0"


which is gained over CGI like so:

if form.getvalue("exposure"):
req["excompensaton"] = form.getvalue("exposure")


Sadly, however, the value needs to be "0", not "0.0" before I can send it over MQTT with JSON.

I've tried:

if form.getvalue("exposure"):
req["excompensaton"] = int(form.getvalue("exposure")


Sadly this came up with the error:


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


I also tried math.floor, but it ended up telling me that it needs to float.

Any help would be really appreciated!!

Answer

If the behavior of int() is what you want, cast to a float first:

int(float(form.getvalue("exposure")))

If you want to be certain of getting one of math.floor() or math.ceil(), you can incorporate those:

int(math.floor(float(form.getvalue("exposure"))))