Delphi/Lazarus: 3 Ways to round a Number to X Decimal Places

Tutorial by Delphian | Last Update on 23/08/2018 | Created on 19/02/2014

Most users of Delphi or even Lazarus are thinking about the function Round when it is about rounding a number. Unfortunately, this function cannot be used to keep some of the decimal places of the original value. Using Round, you can only make 1 from the value 1.2345 and you are not able to round this number to one (1.2), two (1.23) or three decimal places (1.235).

But you can do it in another way. I will show you in this tutorial.

RoundTo

The easiest way is to use the function RoundTo included in Unit Math:

k := 1.2345;
k := RoundTo(k, -2); // k = 1.23

As a first parameter, we are passing our number we would like to round, as a second parameter the number of decimal places, we would like to keep. We have to use negative values at this point in order to round to decimal places. Positive values can be used to round, for example, to hundreds or thousands: RoundTo(12345, 2) = 12300.

Own Function

It is possible, that older versions of the IDE are not supporting the RoundTo method. In this case, we can just use the following calculation to get to our result:

We have to pass our value as well as the number of decimal places to this function and we can use it just like RoundTo.

In this Rounding Tutorial for Delphi and Lazarus has introduced an extension of this function. With the function presented there, you are able to round in both directions: you can round to an arbitrary number of decimal places as well as to positions before the decimal point.

Output directly as String

As a third method, I do not want to withhold the possibility to output a floating point number directly and rounded as a string:

For this, we can use the functions FormatFloat or FloatToStrF, for example.

To FormatFloat, we are passing the format as a first parameter and the number as the second parameter. When using a 0 in the format string, this digit is outputted in each case, when using a hash #, this digit is outputted only if necessary.

FloatToStrF is providing many possibilities to format a number. In our case, we only have to know, that we have to pass our value as first parameter and the number of our desired decimal places as the last one.

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.