Recent

Author Topic: Trunc function  (Read 3531 times)

kjteng

  • Sr. Member
  • ****
  • Posts: 259
Trunc function
« on: November 22, 2017, 05:52:12 am »
Can someone  explain why trunc function reduces the variable aa by 1 in the following code:

procedure TForm1.Button1Click(Sender: TObject);
var aa: double;
begin
  aa:= 10.84;
  showmessage(
              'aa= ' + floattostr(aa) + #13 +
              'aa*100 = ' + floattostr(aa*100) + #13 +
              'round(aa*100) = ' + inttostr(round(aa*100)) + #13 +
              'trunc(aa*100) = ' + inttostr(trunc(aa*100))
              ); 
end; 

Results:
aa=10.84
aa*100=1084
round(aa*100) =1084
'trunc(aa*100) =1083

guest58172

  • Guest
Re: Trunc function
« Reply #1 on: November 22, 2017, 06:00:23 am »
10.84 has no exact IEEE754 representation.
Its value is actually  10.8399999999999999

(see http://www.binaryconvert.com/result_double.html?decimal=049048046056052 for details)

So when you multiply by 100 you get 1083,99999999999999
After truncation you get 1083.

 ;)

kjteng

  • Sr. Member
  • ****
  • Posts: 259
Re: Trunc function
« Reply #2 on: November 22, 2017, 07:04:32 am »
Thank you for your explanation. So I think it is better to use round function in my case.

jamie

  • Hero Member
  • *****
  • Posts: 6129
Re: Trunc function
« Reply #3 on: November 23, 2017, 12:07:52 am »
Yes, rounding is always better if you are interchanging the types back and forth..

I ran into that not to long ago where I was converting Currency type being used for Inches
but had to convert it to Pixels and back again. The values would change as a results.

 Rounding fixes that.. Have a good Turkey day if you're in the states!
The only true wisdom is knowing you know nothing

Thaddy

  • Hero Member
  • *****
  • Posts: 14364
  • Sensorship about opinions does not belong here.
Re: Trunc function
« Reply #4 on: November 23, 2017, 09:41:22 am »
10.84 has no exact IEEE754 representation.
Well you are right if it is a float (as is the case here) but change the double to currency and it has an exact representation because currency is a scaled integer internally.. O:-)
We also have BCD, Of course these also have their limitations, but for the purpose of this example both can represent the exact value.
« Last Edit: November 23, 2017, 09:45:01 am by Thaddy »
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

 

TinyPortal © 2005-2018