0
I need to count the number of decimals in Delphi (10.1) in a string, I will use Edit, validating monetary values when typing, before inserting into Edit.
I can validate if it is a valid Currency, but when comparing it understands 1.23 equal 1.230. Of course, it is valid.
I know there is the option to round, but it is not my goal at this stage, but rather merely count the number of decimal places in a string, to, combining with others functions, prevent the typing of more houses, or characters that are not part of a valid currency, including more zeroes after 1,23.
I researched a lot, and at the moment I got the formula below but I do not believe it is the best (Pog) idea.
function ContarDecimaisTESTE(S: string):string;
//necessita verificar se é um (float,currency) valido antes.
var
Saida: boolean;
i,j, k: word;
w: string;
n: Integer;
begin
k:= 0;
Saida:= false;
n:= length(s);
i:= n;
j:= 0;
for I := 1 to n do
begin
w:=Copy(S,i,1);
j:=j+1;
if (w = ',') then
begin
Saida:=True;
Break;
end;
end;
if (Saida=True) then
begin
k:=(n-j);
end else
begin
k:=0;
end;
Result:=IntToStr(k);
end;
I came up with something better, much like Junior’s idea, but I used more code:
function TamanhoCasasDec(S:string):Int64;//Teste
var
a,b:integer;
c:string;
begin
a:=length(S);
b:=pos(',',S);
try
c:=Copy(FilterChars(S,[',']),1,1);//copiar a primeira virgula, se houver
except
//
end;
if (c = ',') then
begin
Result:=Length(Trim(copy(S, b + 1, a - b)));
end else
begin
Result:=0;
end;
end;
Couldn’t it just be Length(Avalor)-Pos(',', Avalor) ? I don’t notice the use of Copy :)
– Tiago Rodrigues
Yes, the thing about showing a solution so let’s say procedural is that the guy follows the evolution of what is being done. There I even abbreviated some rsrsrsrsrs, I usually move to variable etc...
– Junior Moreira
Thank you Junior Moreira, I arrived at something very similar to what you posted. me also when the head is the limit use quite suggestive variables (vrAntes,vrDepois), I put even showmessage in the middle to keep track. Then I’ll make it simple. The one you made for 12,345 returns 3, but for "12" returns 2. Taking out as much of the wrinkles in my code, I managed to return 0 to "12" or "12," 1 to "12,1" and so on. I believe it will work.
– Metamorfose