# 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..
Asked:
###### Who is Participating?

Commented:
try this

function Cutdecimals(mynum: float): float;
begin

If mynum = 0 then
begin
result:= 0;
exit;
end;

mynum:= mynum*100;
mynum:= Trunc(mynum);
result:= mynum / 100;
end;

David

0

Commented:
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
0

Commented:
try (just from head):
Fields.FieldByName('VALOR_ICMS').DisplayFormat := '#.00';
will only show as 2.58,
but will know as 2.5758
0

Commented:
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;
0

Commented:
I was goinf to say the same as DavidBirch's first comment. The simplest way is best.
0

Commented:
(Fields.FieldByName('VALOR_ICMS') as TFloatField).DisplayFormat := '0.#0';
0

Commented:
I would make it like that :

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

function formatNumber(num: real): real;
begin
result := strToFloat(leftStr(floatToStr(num), pos('.',floatToStr(num))+2));
end;
================================================
0

Commented:
isnt messing around with strings quite a slow way of acheiveing this?

DAvid
0

Commented:
sorry I don't speak very well english.. What do you say ? it is slowly ?...
0

Commented:
are not string functions more slow than doing it with numbers ?
0

Commented:
Yes you have reason.... I've making some test and your function is 35% faster than my...
0

Commented:
Thanks for the points :)

David
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Already a member? Login.

All Courses

From novice to tech pro — start learning today.