How to replace all occurrences of a specific digit in a floating-point number with Pascal

1 Answer

0 votes
program ReplaceDigitsInReal;

function ReplaceAllDigits(num: Real; oldDigit, newDigit: Char): Real;
var
  strNum: string[20];
  i: Integer;
  code: Integer;
  modifiedNum: Real;
begin
  Str(num:0:3, strNum);  { Convert real to string with 3 decimal places }

  for i := 1 to Length(strNum) do
    if strNum[i] = oldDigit then
      strNum[i] := newDigit;

  Val(strNum, modifiedNum, code);  { Convert string back to real }
  if code = 0 then
    ReplaceAllDigits := modifiedNum
  else
    ReplaceAllDigits := 0.0;  { Fallback in case of conversion error }
end;

begin
  Writeln(ReplaceAllDigits(82420.291, '2', '7'):0:3);
  Writeln(ReplaceAllDigits(111.11, '1', '5'):0:3);
end.



(*
run:

87470.791
555.550

*)


 



answered 17 hours ago by avibootz

Related questions

...