Link to home
Start Free TrialLog in
Avatar of fabyola
fabyola

asked on

Getting only 2 numbers after the decimal.

I have a currency like: 2.5758 I need to get all of the numbers before the decimal and only two after the decimal. I tried

FormatFloat('###.##',Fields.FieldByName('VALOR_ICMS').AsFloat) );
and
FormatCurr('0.00', Fields.FieldByName('VALOR_ICMS').AsFloat)

but it rounds to '2.58' and I don´t want it to round. In other words. I want to format my currency number without rounding it..
ASKER CERTIFIED SOLUTION
Avatar of DavidBirch2dotCom
DavidBirch2dotCom

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DavidBirch2dotCom
DavidBirch2dotCom

or this

function Cutdecimals(mynum: float; decimals: integer): float;

      function Exponent(num: integer; Exponent: Integer): integer;
      begin
         Result := 1;

         while Exponent < 0 do
         begin
            Result := Result / num;
            Exponent := Exponent + 1;
         end;

         while Exponent > 0 do
         begin
            Result := Result * num;
            Exponent := Exponent - 1;

         end;
      end;

begin

   If mynum = 0 then
   begin
      result:= 0;
      exit;
   end;
   
   mynum:= mynum*Exponent(10,decimals);
   mynum:= Trunc(mynum);
   result:= mynum /Exponent(10,decimals);
end;

just pass the number you want to format and the number of places to this function

David
try (just from head):
  Fields.FieldByName('VALOR_ICMS').DisplayFormat := '#.00';
will only show as 2.58,
but will know as 2.5758
What do You think anout this

function CutDecimal(str: string):string;
var
  p: integer;
begin
p := Pos(DecimalSeparator,str);   // where is decimal point
if p >= 0 then
  result := Copy(str,1,p+2)           // take 2 after decimal
else
  result := str;                            // no decimal take everything
end;
I was goinf to say the same as DavidBirch's first comment. The simplest way is best.
 (Fields.FieldByName('VALOR_ICMS') as TFloatField).DisplayFormat := '0.#0';
I would make it like that :

================================================
uses strUtils;

function formatNumber(num: real): real;
begin
   result := strToFloat(leftStr(floatToStr(num), pos('.',floatToStr(num))+2));
end;
================================================
isnt messing around with strings quite a slow way of acheiveing this?

DAvid
sorry I don't speak very well english.. What do you say ? it is slowly ?...
are not string functions more slow than doing it with numbers ?
Yes you have reason.... I've making some test and your function is 35% faster than my...
Thanks for the points :)

David