Thursday, August 11, 2022

[FIXED] How to reduce decimals in a POST request

Issue

My POST request sends output with 3 decimals while wanted is 1

I am unable to understand what I should tweak to send 1 decimal point in the POST requests

conn = http.client.HTTPConnection("127.0.0.1:8080")
    for sensor in W1ThermSensor.get_available_sensors():
        print("Sensor %s with id %s  has temperature %.2f" % (sensorNameList.get(sensor.id), sensor.id, sensor.get_temperature()))
        try:
            params = urllib.parse.urlencode({'temperature': sensor.get_temperature()})
            headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
            conn.request("POST", "/WeatherStationServer/api/temperature/"  + sensorNameList.get(sensor.id), params, headers)

The output is 23.357 while it should be 23.3


Solution

Assuming you're referring to the result of sensor.get_temperature(), just format it to the appropriate width, e.g.:

params = urllib.parse.urlencode({'temperature': format(sensor.get_temperature(), '.1f')})

An alternative approach (that leaves it a float) is to use the round function:

params = urllib.parse.urlencode({'temperature': round(sensor.get_temperature(), 1)})

For a case where an actual string is required, I'd recommend formatting it explicitly (as libraries that format a float might not follow Python's rules for formatting, and might end up supplying additional decimal places).

Note that the correct rounding for both cases produces 23.4, not 23.3. If you really want to truncate, not round, you're stuck being a bit ugly to multiply, truncate, and divide back, e.g.:

params = urllib.parse.urlencode({'temperature': round(int(sensor.get_temperature() * 10) / 10, 1)})

Since converting to int explicitly removes trailing decimal places, this will compute the following values:

  1. After multiplication 233.57
  2. After int conversion, 233
  3. After division, 23.3
  4. After round (necessary to handle cases where floating point imprecision might make dividing by 10 produce more than one decimal point): 23.3


Answered By - ShadowRanger
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.