How to replace a digit in a floating-point number by index with Pascal

1 Answer

0 votes
program ReplaceFloatDigitProgram;

{$APPTYPE CONSOLE}

function ReplaceFloatDigit(number: Real; position: Integer; newDigit: Char): Real;
var
  strNum: String;
  modified: String;
  resultNum: Real;
  code: Integer;
begin
  (* Validate newDigit *)
  if (newDigit < '0') or (newDigit > '9') then
  begin
    writeln('Error: Replacement must be a digit (0-9).');
    halt(1);
  end;

  (* Convert number to string with fixed precision *)
  Str(number:0:10, strNum);   (* 10 decimal places *)

  (* Validate position (Pascal strings are 1-based) *)
  if (position < 1) or (position > Length(strNum)) then
  begin
    writeln('Error: Position out of range.');
    halt(1);
  end;

  (* Ensure position points to a digit *)
  if (strNum[position] = '.') or (strNum[position] = '-') then
  begin
    writeln('Error: Position points to non-digit character.');
    halt(1);
  end;

  (* Replace digit *)
  modified := strNum;
  modified[position] := newDigit;

  (* Convert back to real *)
  Val(modified, resultNum, code);
  if code <> 0 then
  begin
    writeln('Error: Conversion failed.');
    halt(1);
  end;

  ReplaceFloatDigit := resultNum;
end;

var
  num, result: Real;
  pos: Integer;
  newDigit: Char;
begin
  num := 89710.291;
  pos := 3;          
  newDigit := '8';

  result := ReplaceFloatDigit(num, pos, newDigit);
  writeln('Modified number: ', result:0:3);
end.



(*
run:

Modified number: 89810.291

*)


 



answered Nov 17, 2025 by avibootz
edited Nov 17, 2025 by avibootz
...