Reputation: 13
How to truncate a floating point number up to N decimal places in Prolog?
Is there any built-in tool for this?
Upvotes: 1
Views: 953
Reputation: 419
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.
Upvotes: 1