Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 6 months ago.
how do I limit the amount of trailing zeros of a float and double?
Creating a json object was relatively simple. The json string is: {"sensorBoardName":["SensorBoard1"],"sensor":{"pH":0.000000}} The "pH": json value should be 0.00 instead of 0.000000. Is there anyway to limit the amount of trailing 0s float produces? Does anyone know if there is a configuration setting in the MbedJSONValue.h library to limit the amount of trailing zeros?
#include "mbed.h" #include "MbedJSONValue.h" MbedJSONValue SensorData; float phSensor = 0.00; int main() { char *sbNameKey = "SensorBoardName"; char sbNameValue[BUFSIZ]; MbedJSONValue SensorData; std::string s; /* * Read a configuration file from a mbed. */ if (!cfg.read("/local/settings.cfg")) { error("Failure to read a configuration file.\n"); } /* * Get a configuration value. * Then attach the sbNameValue to SensorData json */ if (cfg.getValue(sbNameKey, &sbNameValue[0], sizeof(sbNameValue))) { //printf("'%s'='%s'\n", sbNameKey, sbNameValue); //Create sensorBoardName value to json object SensorData["sensorBoardName"][0] = sbNameValue; } SensorData["sensor"]["pH"] = phSensor; //serialize it into a JSON string s = SensorData.serialize(); printf("json: %s\r\n", s.c_str()); while(1) { } }
1 Answer
11 years, 6 months ago.
I edited line 91 in MbedJSONValue.cpp from:
sprintf(buf, "%f", _value.asDouble);
to:
sprintf(buf, "%.2f", _value.asDouble);
The %.2f trimmed the double value to just two decimals places.
Thank you Samuel Mokrani for guiding me in the right direction.