# Arduino sketches experts? :) decimal places

Hey folks, need bit of help with formatting variables.

Is there some elegant way how to do exactly what this does

``````Serial.println(123.422,1);
``````

which outputs to the console

``````123.4
``````

But I need more like this

``````float value = 123.455;
value = (value,1);

output += String(value);
``````

But it does not work, it’s just doing 1 in the output

I kind of wanted to avoid doing this

``````float x = 123.455;
x = x + 0.05;       //123.506
x = x*10.0; //1235.06
int y = (int)x; //1235
float z = (float)y/10.0; //123.5
``````

Thanks for tips

Hi Kriznik,

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.

In this case I have written a function for you:

``````float DecimalRound(float input, int decimals)
{
float scale=pow(10,decimals);
return round(input*scale)/scale;
}
``````
``````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.

1 Like

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 