StrtoFloat Conversion Library

Post your requests and ideas on the future development of mikroPascal PRO for AVR.
Post Reply
Author
Message
corado
Posts: 399
Joined: 28 Mar 2009 11:03

StrtoFloat Conversion Library

#1 Post by corado » 13 Mar 2014 21:54

hallo,
for long long time, Mikroe says, they are working at a StrToFloat conversion...but nothing happens :-(

If i work with this..I have Problems...
It converts 1 in 1 and 1.0 in 1.0 but
it goes to 1.65 in 1.65...
but 1.66 doesn't work till 2 then it works again till 2.65 at 2.66 it's wrong again...till 3...to 3.65....and so on :-(

Code: Select all

function StrtoFloat(var data_str4 : string[17]) : real;
var txt10 : string[10];
    lungime, lungime1 : byte;
    pt1, pt2 : ^byte;
begin
  result := 0.;
  lungime := StrLen(data_str4);
  if (lungime = 0) or (lungime > 17) then exit;
  lungime1 := StrChr(data_str4,'.');
  if lungime1 = 0 then exit;
  txt10 := '00000';
  pt1 := @data_str4[lungime1];
  pt1^ := 0;
  pt1 := pt1 + 1;
  pt2 := @txt10;
  inc(lungime1);
  while lungime1 < lungime do
    begin
      pt2^ := pt1^;
      pt2 := pt2 + 1;
      pt1 := pt1 + 1;
      inc(lungime1);
    end;
    if data_str4[0] = '-' then result := real(StrtoInt(data_str4)) - real(Strtoword(txt10))/100000.0
    else result := real(StrtoInt(data_str4)) + real(Strtoword(txt10))/100000.0;
end;

User avatar
dejan.odabasic
mikroElektronika team
Posts: 2649
Joined: 30 Apr 2012 14:20

Re: StrtoFloat Conversion Library

#2 Post by dejan.odabasic » 19 Mar 2014 11:30

Hello,

Try using this function for String to float/real conversion:

Code: Select all

program StrtoFloatTest;
function StrtoFloat(var data_str4 : string[17]) : real;
    var len, dotpos, n : byte;
begin
    result := 0.0;
    dotpos := 0;
    len := strlen(data_str4);
    if ((data_str4[0]  = '-') OR (data_str4[0] = '+')) then
        n:=1
    else
        n:=0;        
    while ( n < len) do
    begin
      if (data_str4[n] = '.') then
        dotpos := len - n  - 1
      else
        result := result * 10.0 + (data_str4[n]-'0');
      inc(n);
    end;
    while (dotpos <> 0) do
    begin
      dec(dotpos);
      result := result / 10.0;
    end;
    if (data_str4[0] = '-') then
        result := -result;
end;

var nn : real;
begin
  nn := StrtoFloat('-12345.66');
  nn := StrtoFloat('.68');
  nn := StrtoFloat('-.123');
end.
Best regards.

corado
Posts: 399
Joined: 28 Mar 2009 11:03

Re: StrtoFloat Conversion Library

#3 Post by corado » 08 Apr 2014 17:57

great, this works fine

Post Reply

Return to “mikroPascal PRO for AVR Wish List”