Truncate a floating point number in prolog

916 views Asked by At

How to truncate a floating point number up to N decimal places in Prolog?

Is there any built-in tool for this?

1

There are 1 answers

3
Iqazra On BEST ANSWER

Actually, it is easy to define a predicate truncate/3 in Prolog. Let's say that we want truncate a real number X up to N decimal places and store its result in Result. Using the mathematical function for truncation in this Wikipedia site, we can define the predicate as follows:

    % truncation for positive numbers
    truncate(X,N,Result):- X >= 0, Result is floor(10^N*X)/10^N, !.

    % truncation for negative numbers
    truncate(X,N,Result):- X <0, Result is ceil(10^N*X)/10^N, !. 

I use cut because the two above cases are mutually exclusive.