Floating point numbers are not decimal numbers – they can indeed be quite difficult to work with.
The Arduino libraries have a limited subset of what’s normally available in C on bigger computer systems.
Even so, there is no C function to round to a particular decimal place.
But, the beauty of C, like most other proper programming languages, is that if a function is missing you can simply write your own! There is a round() function we can use to round to the nearest whole number. With multiplication and division we get the result you’re asking for.
float value = 123.455;
value = DecimalRound(value,1);
String output;
output += String(value);
…produces 123.4.
But, before you use it, here’s a question you should ask yourself first:
Why are you trying to round the float value itself? Rounding adds an error every time. It’s much better to round it only when it needs to be displayed, and that’s what Serial.println(float,decimals) is for, which you already know about. I recommend leaving full precision in the variables until you present it to the user.
Thanks @leif I’m rounding the ouput indeed as those are temp/humidity etc. values from BME680 sensors which came in in like 5 decimal places, which is definitely not needed for my usage
Thanks for nice function! works like a charm. I hoped that there is oneliner indeed, but this works just fine
+1