tags:

views:

189

answers:

4

Hi, How to convert a integer to float in Delphi?

E.g int_h:= int_var/1.5* int_var;

A: 

i*1.0 should convert it to a floatingpoint number. Any calculation involving floatingpoint numbers of any type gets implicitly converted to extendend and then implicitly converted to the desired result type on assignment. In contrast to C/C++ all calculations happen in Extended(80 bit float, the internal format of the x87 floatingpoint unit) and are converted back later.

real(i) might work too.

CodeInChaos
I would like it in the other way round.
Aftershock
I'm too stupid to read :-/
CodeInChaos
it does but real does not work
Aftershock
+1  A: 

You can do:

myFloat := myInteger;
Gamecat
That typecast is not valid: E2089 Invalid typecast.
Barry Kelly
+1  A: 

3 possible ways, depending on the kind of expressions you have.

var
  Float: Double;
  Int1: Integer;
  Int2: Integer;
begin
  Int1 := 925;
  Int2 := 21;
  Float := Int1; // simple form: assign it
  Writeln(Float);
  Float := Int2 / Int1; // floating point division: assign it
  Writeln(Float);
  Float := (1.0 * Int2) * Int1; // integer operator: multiply by 1.0 and add parenthesis
  Writeln(Float);
end.

Output:

 9.25000000000000E+0002
 2.27027027027027E-0002
 1.94250000000000E+0004
Jeroen Pluimers
First a +1, then a -1; I'd love motivation for both: it helps me write better answers.
Jeroen Pluimers
+1  A: 

Integer to Float

There is not need to cast anything, just assign

Float1 := Integer1;

Your question seem be Float to Integer

Two options

Integer1 := Trunc(Float1); //truncate 

or

Integer1 := Round(Float1); //Round
APZ28
The opposite of Trunc() is actually Ceil(). Trunc() will round towards zero, Ceil() will round either towards +Infinity (if it is a positive number) or -Infinity (if negative).
Trinidad
No Ceil will always round to +inf, Floor will always round to -inf, and Trunc always to 0. So the opposite of Ceil() isn't Trunc, but Floor.
CodeInChaos
Yes, you're correct =) Sorry.
Trinidad