round(@number, @precision_number)

If the argument is a floating point value then it is rounded with the specified precision. With the 'precision_number' argument it is possible to specify the number of integer characters behind the decimal point after rounding. If the value of the 'precision_number' argument is 2 then the first 3 integers behind the decimal point are used for rounding.

The round/2 predicate is very useful for working with floating-point numbers which have a limited accuracy, like doing calculations with money values. Money values usually have an accuracy of 2 decimals and the last 3 decimals must be used for rounding. For example: somebody has worked 2 hours and 23 minutes and per hour he/she gets paid 11.55$. The calculation is (2 + (23 / 60)) * 11.55, and the result is 27.5275. There are four numbers behind the decimal point and it must be rounded to two numbers, the correct procedure in this case is to use the first three numbers behind the decimal point (the last '5' is ignored) for rounding the number, the result of round( 27.5275, 2) is 27.53$.

The prolog flag num_digits determines the maximum number of decimals a number can have when it is converted to a readable representation, it can cause the result of an arithmetic expression to be rounded again.

see also: arithmetic in Prolog round/1

Examples
X is round(636.06 *0.23, 0). succeeds, X is 146
X is round(636.06 *0.23, 1). succeeds, X is 146.3
X is round(636.06 *0.23, 2). succeeds, X is 146.29
X is round(636.06 *0.23, 3). succeeds, X is 146.294
X is round(636.06 *0.23, 4). succeeds, X is 146.2938

 

Exceptions
the precision argument is a negative number an evaluation_error(negative, Goal) exception is thrown, where Goal is unified with the call to round/2
the precision argument is larger than 50 a domain_error(value, Goal) exception is thrown, where Goal is unified with the call to round/2
the result exceeds the floating point range an evaluation_error(int_overflow) exception is thrown

 

 

info@trinc-prolog.com