program FirstDecimalDigit;
{$mode objfpc}{$H+}{$H-}
{
This program demonstrates how to extract the first digit
after the decimal point from a floating‑point number.
Approach:
---------
1. Use Frac() to obtain only the fractional part of the value.
2. Multiply the fractional part by 10 to shift the first decimal digit
into the integer range.
3. Truncate using Floor() to avoid rounding issues.
4. Convert to integer and return the digit.
This keeps the logic numeric, efficient, and expressive.
}
uses
Math;
{
getFirstDecimalDigit:
----------------------
Returns the first digit after the decimal point of a floating‑point number.
}
function getFirstDecimalDigit(value: Double): Integer;
var
fractional : Double;
begin
fractional := Frac(Abs(value)); { isolate fractional part }
Result := Floor(fractional * 10); { shift and truncate }
end;
var
number : Double;
digit : Integer;
begin
number := 123.456; { example input }
digit := getFirstDecimalDigit(number);
WriteLn('Number: ', number:0:3);
WriteLn('First digit after decimal: ', digit);
end.
{
run:
Number: 123.456
First digit after decimal: 4
}