Convert or Trim After Round

Trying to find a solution to trimming a float number after rounding. I always run into the same problems when doing stuff on this platform which is not being able to use additional libraries that are not included in the cloud web IDE when I use the various ways of math already in popular use by C++… So what does everyone use on default for trimming a string or a number before it’s a string.

Here is my line of code.

    double USDperBTC = round(1/atof(data)*100)/100;// Rounds fine to two decimal places but just need to trim after two decimal places...

However to simplify just keep in mind a number that displays “6500.670000” needs to be displayed as “6500.67”…

This has nothing to do with the platform but is the standard behaviour for floating point variables on any platform.
Floating point variables are unable to store some values exactly due to the way how numbers are stored in binary form.
So you can try as you might to store an exact value inside a double but won't be able to.

For calculations it won't make any difference whether you get some deviation in the insignificant decimal places.
If you need your exact value for human reading you can go the standard C/C++ way

  char strFloat[64];
  double f = 6500.67;
  snprintf(strFloat, sizeof(strFloat), "raw: %f, rounded: %.2f", f, f);
  Serial.println(strFloat);
2 Likes

Thanks this works as needed you are awesome!!. I’ll have to dig deeper into more c/c++ as I am used to a load of other programming languages that do not require setting memory as with the [64]…

char strFloat[64];
double USDperBTC = round(1/atof(data)*100)/100;// Rounds fine but just need to trim after two decimal places...
snprintf(strFloat, sizeof(strFloat), "%.2f", USDperBTC, USDperBTC);
textToDisplay = strFloat;// Display somewhere that displays a string!

I would drop the rounding completely as it only introduces extra inaccuracies and doesn’t benefit the result.

In my experience, depending on the implementation, the printf family of functions usually round to the specified precision.

I ran into a similar issue, but I used int():
double LM35Temp;
LM35Temp = int(ReadTemp() * 100) / 100;

It works on most of my applications. A different program, on a different device, I get a few zeros added after the decimal point. It did truncate the number enough, so I stopped fiddling with it.

That would work too I would just need to trim the extra still to two decimals places. Since it's a dollar value in this case. The number is actually more like "6500.670937" before rounding.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.