Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trunc() function

look the follow code, why the result of Trunc function is different?

procedure TForm1.Button1Click(Sender: TObject);
var
  D: Double;
  E: Extended;
  I: Int64;
begin
  D := Frac(101 / 100) * 100;
  E := Frac(101 / 100) * 100;
  I := Trunc(D);
  ShowMessage('Trunc(Double): ' + IntToStr(I));  // Trunc(Double): 1
  I := Trunc(E);
  ShowMessage('Trunc(Extended): ' + IntToStr(I)); // Trunc(Extended): 0
end;
like image 367
Leo Avatar asked Sep 09 '09 08:09

Leo


People also ask

What is the value of TRUNC ()?

A positive number truncates digits to the right of the decimal point, and a negative number replaces digits to the left of the decimal point. The default value is zero (0). TRUNC(15.79) returns the value 15 .

How does truncate work in Excel?

Truncating in Excel, also known as the TRUNC function, is used to simplify data. It allows you to estimate a number without determining the exact digits after a certain point in the string of integers. It doesn't round off numbers but instead displays a number to a specified number of decimal places.

What is the use of TRUNC function in Oracle?

The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is omitted, then n1 is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left of the decimal point.

What is TRUNC in C++?

The trunc() function in C++ rounds the argument towards zero and returns the nearest integral value that is not larger in magnitude than the argument. The trunc() function in C++ rounds the argument towards zero and returns the nearest integral value that is not larger in magnitude than the argument.


1 Answers

Formatting functions don't always display the actual numbers (data).
Real numbers and precision can be tricky.

Check out this code where I use more precision on what I want to see on the screen:

  D := Frac(101 / 100);
  E := Frac(101 / 100);
  ShowMessage(FloatToStrF(D, ffFixed, 15, 20));
  ShowMessage(FloatToStrF(E, ffFixed, 18, 20));

It appears that D is something like 0.010000000000 while E is like 0.00999999999.

Edit: Extended type has better precision than Double type. If we try to display the values of D and E with FloatToString() we'll probably get the same result, even though the actual values are not the same.

like image 178
Nick Dandoulakis Avatar answered Sep 29 '22 09:09

Nick Dandoulakis