Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,140 questions

56,014 answers

573 users

How to extract the first digit from a floating-point number in Pascal

2 Answers

0 votes
program FirstDigitDemo;

uses
  Math;  { for Abs and Floor }

function GetFirstDigit(num: Double): Integer;
begin
  { Handle zero explicitly }
  if num = 0.0 then
  begin
    GetFirstDigit := 0;
    Exit;
  end;

  { Work with absolute value to ignore sign }
  num := Abs(num);

  { Shift decimal point until number >= 1 }
  while num < 1.0 do
    num := num * 10.0;

  { Shift until number < 10 }
  while num >= 10.0 do
    num := num / 10.0;

  { Floor to get the integer digit }
  GetFirstDigit := Trunc(Floor(num));
end;

var
  value: Double;
  firstDigit: Integer;

begin
  value := 48724.928;
  firstDigit := GetFirstDigit(value);
  writeln('First digit: ', firstDigit);

  firstDigit := GetFirstDigit(0.9761);
  writeln('First digit: ', firstDigit);
end.



(*
run:

First digit: 4
First digit: 9

*)



answered Nov 17, 2025 by avibootz
0 votes
program ExtractFirstDigit;

function GetFirstDigit(num: Double): Integer;
var
  s: string;
  i: Integer;
begin
  { Handle negative numbers }
  num := Abs(num);

  { Convert number to string }
  Str(num:0:6, s);  { format with 6 decimal places }

  { Scan string for first digit }
  for i := 1 to Length(s) do
  begin
    if (s[i] >= '0') and (s[i] <= '9') then
    begin
      GetFirstDigit := Ord(s[i]) - Ord('0');
      Exit;
    end;
  end;

  { Error case }
  GetFirstDigit := -1;
end;

var
  value: Double;
  firstDigit: Integer;

begin
  value := 48724.928;
  firstDigit := GetFirstDigit(value);
  writeln('First digit: ', firstDigit);

  firstDigit := GetFirstDigit(0.9761);
  writeln('First digit: ', firstDigit);
end.



(*
run:

First digit: 4
First digit: 0

*)


 



answered Nov 17, 2025 by avibootz
...