Hosted by
 |
with Ada.Text_IO; use Ada.Text_IO;
package body Digits_Strings is
function To_Number
(Value : in String)
return Number
is
Index : Positive := Value'First;
Result : Number := 0.0;
Negative : Boolean := Value(Index) = '-';
Dot_Found : Boolean := False;
Factor : Number := 1.0;
I : Integer;
begin
if Negative then Index := Index + 1; end if;
loop
exit when Index > Value'Last;
if Value(Index) = '.' then
Dot_Found := True;
Index := Index + 1;
end if;
exit when not (Value(Index) in '0' .. '9');
I := Character'Pos(Value(Index)) - Character'Pos('0');
if not Dot_Found then
Result := Result * 10.0 + Number(I);
else
Factor := Factor / 10.0;
Result := Result + Factor * Number(I);
end if;
Index := Index + 1;
end loop;
if Negative then Result := -Result; end if;
return Result;
end To_Number;
function To_String_Internal
(Value : in Number;
Done : in Number;
Divisor : in Number;
Tolerance : in Number := 0.00005)
return String
is
Rest : Number := Value - Done;
I : Integer := Integer(Number'Floor(Rest / Divisor));
C : Character := Character'Val(Character'Pos('0') + I);
Done2 : Number := Done + Number(I) * Divisor;
begin
if Rest < Tolerance and Divisor < 0.5 then
return "";
elsif Divisor > 0.5 then
return C &
To_String_Internal(Value, Done2, Divisor / 10.0, Tolerance);
elsif Divisor > 0.05 then
return "." & C &
To_String_Internal(Value, Done2, Divisor / 10.0, Tolerance);
else
return C &
To_String_Internal(Value, Done2, Divisor / 10.0, Tolerance);
end if;
end To_String_Internal;
function To_String
(Value : in Number;
Tolerance : in Number)
return String
is
Divisor : Number := 1.0;
begin
if Value < 0.0 then
return "-" & To_String(-Value);
elsif Value < Tolerance then
return "0";
else
while Divisor <= Value loop
Divisor := Divisor * 10.0;
end loop;
return To_String_Internal(Value, 0.0, Divisor / 10.0, Tolerance);
end if;
end To_String;
function To_String
(Value : in Number)
return String is
begin
return To_String(Value, 0.00001);
end To_String;
end Digits_Strings;
|