program GetNthDecimalDigit;
{$mode objfpc}{$H+}
uses
SysUtils, Math;
{
Returns the Nth digit after the decimal point.
Parameters:
Value - Floating-point number to inspect.
Position - Digit position after the decimal point (1-based).
Returns:
The requested digit (0..9).
Notes:
- Returns 0 if the digit does not exist.
- Raises an exception if Position is less than 1.
}
function GetNthDecimalDigit(const Value: Double;
const Position: Integer): Integer;
var
NumberStr: String;
DecimalPos: Integer;
DigitIndex: Integer;
begin
if Position < 1 then
raise Exception.Create(
'Position must be greater than zero.');
{
Convert the absolute value to a string.
ffFixed = fixed-point notation
18 = total significant digits
15 = digits after decimal point
}
NumberStr := FloatToStrF(
Abs(Value),
ffFixed,
18,
15
);
{ Find decimal separator }
DecimalPos := Pos(FormatSettings.DecimalSeparator,
NumberStr);
if DecimalPos = 0 then
begin
Result := 0;
Exit;
end;
{ Index of the requested digit }
DigitIndex := DecimalPos + Position;
if DigitIndex > Length(NumberStr) then
begin
Result := 0;
Exit;
end;
Result := Ord(NumberStr[DigitIndex]) - Ord('0');
end;
var
Number: Double;
I: Integer;
begin
Number := 123.456789;
WriteLn('Number: ', FormatFloat('0.000000', Number));
WriteLn;
for I := 1 to 6 do
begin
WriteLn(
I,
' digit after decimal = ',
GetNthDecimalDigit(Number, I)
);
end;
WriteLn;
WriteLn('Additional Examples');
WriteLn('-------------------');
WriteLn(
'123.456789, position 4 -> ',
GetNthDecimalDigit(123.456789, 4)
);
WriteLn(
'-98.7654, position 2 -> ',
GetNthDecimalDigit(-98.7654, 2)
);
WriteLn(
'1.2, position 5 -> ',
GetNthDecimalDigit(1.2, 5)
);
end.
{
run:
Number: 123.456789
1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9
Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0
}