1

Is there some kind of implemented function that would allow to transform an integer to float and vice versa?

I managed to write a short function that transforms an integer to float:

function Transform(First: Integer) return Float is
    A: Integer := First;
    B: Float := 0.0;
begin
    For_Loop:
    for I in Integer range 1 .. A loop
        B := B + 1.0;
    end loop For_Loop;
    return B;
end Transform;

But I don't know how to go from Float to Integer.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
John Mayne
  • 237
  • 1
  • 3
  • 14
  • 4
    Aside from being horribly slow for large values this can be badly wrong. `Integer` range and `Float` precision are implementation-defined subject to standard minima, but for many platforms (such as x86) `Integer` is 32 bits and `Float` is IEEE single with 23-plus-hidden-bit significand; in this case your algorithm 'saturates' all integer values over 2\*\*24 down to 2\*\*24. – dave_thompson_085 Jul 31 '16 at 03:08

2 Answers2

9

Ada can do explicit type conversions

with Ada.Text_IO; use Ada.Text_IO;
procedure Convert is
  A: Integer:= 4;
  B: Float;
  C: Float := 6.8;
  D: Integer;
begin
  B := Float(A);
  Put_Line(Float'Image(B));

  D:= Integer(C);
  Put_Line(Integer'Image(D));
end Convert;
James K
  • 3,692
  • 1
  • 28
  • 36
  • 3
    See also [*4.6 Type Conversions*](http://www.ada-auth.org/standards/12rm/html/RM-4-6.html#I2915). – trashgod Jul 31 '16 at 00:30
0

Barnes says that to convert from Integer to Float you should multiply by 1.0. as root Real * Root Integer is allowed and returns the root Real.

Mark
  • 1